I've built a form, it works out a total, then another total, takes 4% away from the total and then gives the final value.
My issue is that i do not receive the decimal places to the calculation, so for example if the total price is £500 and the 4% removal is $52.10 my total value is 53, not 52.10.
JSFiddle: https://jsfiddle.net/znc93w90/1/
jQuery(document).ready(function(){
var insOn = 15;
var insOff = 0;
var insuranceCover = 0;
var qtyy=jQuery("#wpforms-2562-field_5");
var completetotal=jQuery("#totaltwo");
qtyy.keyup(function(){
//NewValue = 4% of the total
var newValue = parseInt(completetotal.val()) * 0.04;
//FinalValue = Total - 4% - 25
var finalValue = parseInt(completetotal.val()) - parseInt(newValue) - 25;
//Spit the totals out
jQuery('#totalfinal').text(finalValue.toFixed(2));
jQuery('#testing').text(newValue.toFixed(2));
jQuery('#testingtwo').val(finalValue.toFixed(2));
});
});
Just don't parse your numbers to an Int:
//NewValue = 4% of the total
var newValue = completetotal.val() * 0.04;
//FinalValue = Total - 4% - 25
var finalValue = completetotal.val() - newValue - 25;
Related
I will be making a CI calculator, here is a compounded interest formula that i have obtained: Total Amount = P(1+(R/100))n
Some details on each statement above:
CI = Compound Interest, P = Principal or Sum of amount, R = % Rate
per annum, n = Time Span in years, Total Amount = P +
CI
But i can't figure it out how to get the compounded value?
It should output Compounded value: 1691.13
var typ = 1;
var r = 6; // % Rate per annum
var p = 5000; // Principal or Sum of amount
var n = 5; // Time Span in years
var result = Math.pow(1 + ((r/typ)/100), typ * n);
var c = p * result;
var e = c; // Output is 6691.13, Compounded value: 1691.13
alert(e);
I expect the output to be 1691.13
Your c variable will contain the full amount after interest has been accrued, like in a bank account - it'll contain the initial amount and the accrued amount. Subtract the initial value from it to get only the accrued amount. Using descriptive variable names will probably make things a lot more clear:
var typ = 1;
var annualInterest = 6; // % Rate per annum
var initialAmount = 5000; // Principal or Sum of amount
var years = 5; // Time Span in years
var multiplier = Math.pow(1 + ((annualInterest/typ)/100), typ * years);
const finalAmount = initialAmount * multiplier;
const earnedInterest = (finalAmount - initialAmount).toFixed(2);
console.log(earnedInterest);
You can also subtract 1 from the multiplier to obtain the earned interest only, rather than subtracting the initialAmount afterwards:
var typ = 1;
var annualInterest = 6; // % Rate per annum
var initialAmount = 5000; // Principal or Sum of amount
var years = 5; // Time Span in years
var multiplier = Math.pow(1 + ((annualInterest/typ)/100), typ * years) - 1;
const earnedInterest = (initialAmount * multiplier).toFixed(2);
console.log(earnedInterest);
You can also use toFixed(2) to take only 2 decimal places.
Your c varaible is the Total Amount
now, you can use your equation: Total Amount = P + CI
it make: CI = Total Amount - P
So 6691.13 - 5000 = 1691.13
My price: 20
Quantity: 2
Tax: 10%
How to calculate this?
I dont know the formula to do this calculation.
In your case:
var priceWithTax = 20 * 1.10 * 2;
or more general:
var priceWithTax = price * (1 + taxPercentage / 100) * amount;
The order of factors doesn't matter.
Just multiply all of them together:
const price = 20;
const quantity = 2;
const taxRate = 0.1;
const tax = price * quantity * taxRate
const totalPrice = price * quantity + tax;
var price = 20;
var tax = 0.1;
var qty = 2;
//amount includes the tax
var amountWithTax = (qty * price) / (1 - 0.1);
console.log(amountWithTax);
//amount you get after you pay the tax
var amountAfterDeductTax = amountWithTax - (amountWithTax * tax) ;
console.log(amountAfterDeductTax)
I'm trying to apply a discount to a selection in JavaScript, but for some reason, my code is returning the total to subtract as the total price:
selectone = parseInt(selectone);
var textarea = document.getElementById('discount');
var word = '15off';
var textValue=textarea.value;
if (textValue.indexOf(word)!=-1)
{
var discval = parseFloat(selectone);
var num = parseInt(discval);
var retval = num - (num * .15);
} else {
var retval = 0
}
var total = selectone - retval;
document.getElementById("rettotal").innerHTML = "Price starts from £" + total;
}
For example, if something costs £100 and a 15% discount is applied, the total will be '£15' instead of '£100' ('retval' instead of 'total')
Is there something I've missed in this, or is something missing?
I've not done maths in JavaScript much so a bit over my head!
Many thanks
You've logic problem in math part.
You want to get amount after discount.
You're doing it:
var retval = num - (num * .15); // 100 - (100 * .15) = 85
But after You're removing discount from amount:
var total = selectone - retval; // 100 - 85 = 15
So here is the fix:
var price = parseFloat(selectone);
var discount = (textValue.indexOf('15off') != -1)?
price * .15
: 0;
var total = price - discount; // 100 - 15 = 85
or just be simple (if discount applies once):
var total = parseFloat(selectone);
if(textValue.indexOf('15off') != -1) {
total *= .85;
}
let's be flexible (applying multiple discounts to price):
var textValue = 'take this 15off and this 10off';
var price = parseFloat(1000);
var total = price;
total-= (textValue.indexOf('15off') != -1)?
price * .15
: 0;
console.log(total);
total-= (textValue.indexOf('10off') != -1)?
price * .15
: 0;
console.log(total);
Because... math.
selectone = parseInt(selectone);
...
var discval = parseFloat(selectone); // doesn't change the things, it's an int already
var num = parseInt(discval); // so num is essentially discval, which is selectone
var retval = num - (num * .15); // here you get 85% of num...
...
var total = selectone - retval; // here you get 15% back
The fix is to remove num - from retval, so as var retval = num * .15;
The code you've shown could be compressed to this:
var textarea = document.getElementById('discount');
var total = parseFloat(selectone)*(1-0.15*textarea.value.includes("15off"));
document.getElementById("rettotal").innerHTML = "Price starts from £" + total;
Or, if you have problems with includes() not being supported by your browser (in case it's IE), you could also use match():
var total = parseFloat(selectone)*(1-0.15*(textarea.value.match("15off")|0));
You have a JavaScript operator precedence and meaning problem there. That's syntax mistake on your part.
In an expression like this:
x - y = z
You are thinking that:
z = x - y //but it's not.
What you are really saying is:
y = z and x = x - z
lets say we have datas:
var datas = [{animal:"chicken"}, {animal: "cow"}, {animal: "duck"}];
var after_massage = [];
datas.forEach(function(key){
after_massage.push({animal: key.animal}, {percentage: randomPercent(); })
})
Right now i dont know how to give each object got random percentage and total of 3 object cant be more than 100% percent
You can accomplish this by keeping track of a max number that your random number can hit and then keep decrementing. Theoretically, this can go on infinitely:
var datas = [{animal:"chicken"}, {animal: "cow"}, {animal: "duck"}];
var after_massage = [];
var max = 1;
var getRandomPercent = function(max) {
var percentage = Math.random() * (max - 0) + 0;
// every time we generate a random number, we'll decrement
max = max - percentage;
return percentage;
}
datas.forEach(function(key){
after_massage.push({animal: key.animal, percentage: getRandomPercent(max) })
});
console.log(after_massage);
See JSFiddle
I am not sure what you want to achieve so its a little hard to formulate an answer. But you can go about it in 2 ways I could think of.
1) Split 1 by the length of your array (i.e. 1/3 = 33%) and then generate a random number like so:
function generateRandomPercentage(arrayLength){
var maxPercentageValue = (1 / arrayLength) * 100;
return Math.floor(Math.random() * maxPercentageValue );
}
2) Have a diminishing percentage value based on what percentage is left over.
var percentUsed = 0;
datas.forEach(function(key){
var randomPercent = generateRandomPercentage(percentageUsed );
percentUsed = percentUsed + randomPercent ;
after_massage.push({animal: key.animal, percentage: randomPercent })
});
function generateRandomPercentage(percentageRemaining){
var maxPercentageValue = (100 - percentageRemaining);
return Math.floor(Math.random() * maxPercentageValue );
}
Both methods will ensure you have a sum total of less than 100%.
You want got random percentage and total of 3 object cant be more than 100% percent ,so need to reduce percent by got random number like this...
var datas = [{animal:"chicken"}, {animal: "cow"}, {animal: "duck"}];
var after_massage = [];
var percent = 100,
r = 0;
datas.forEach(function(key){
after_massage.push({animal: key.animal,percentage: randomPercent()});
})
function randomPercent(){
percent = percent - r ;
r = Math.floor(Math.random() * percent);
return r;
}
console.log(after_massage);
You will see total percent of 3 object is not more than 100.
I have a script that calculates totals based on price, quantity, tax and shipping cost. When I attempt to add them together I receiving high numbers for total cost
Here is the script:
function calculate() {
var total = 0;
var shiptotal = 0;
var subtotal = 0;
var taxtotal = 0;
var taxrate = .078;
$('.button-click').each(function () {
var amt = parseInt($(this).prev().val());
var qty = parseInt($(this).parent().find(".quantity").val());
var ship = parseInt($(this).parent().find(".ik-ship").val());
shiptotal += (ship * qty);
subtotal += (amt * qty);
taxtotal += ( (amt * qty) * taxrate);
total += ( subtotal + shiptotal + taxtotal );
});
$('#Amount').val(total.toFixed(2));
$('.total-amount').html( total.toFixed(2) );
$('.sub-total-amount').html( subtotal.toFixed(2) );
$('.shipping-amount').html( shiptotal.toFixed(2) );
$('.tax-amount').html( taxtotal.toFixed(2) );
}
A product that cost $62.00 and has $3.00 in shipping comes out like this:
SUB-TOTAL: 62.00
SHIPPING: 3.00
TAX: 4.84
TOTAL: 1257.05 <-- incorrect total -->
I may have been in front of the computer for too long but how do I solve this problem? Please provide an example.
Use integer math by multiplying the numbers for 1000.