I simply want to add to numbers (currency if you will) like 1.5 and 1.47 together and have it equal 1.97.
How is this accomplished? I did not know I did not know how to do this! :)
var discountAmount = 0;
var ogCookie = < %= strJsonCookie % >
for (var i = 0; i < ogCookie.products.length; i++) {
discountAmount = parseFloat(discountAmount) + parseFloat(ogCookie.products[i].discount_amount);
}
alert(discountAmount);
I simply want to add to numbers (currency if you will) like 1.5 and 1.47 together and have it equal 1.97.
How is this accomplished? I did not know I did not know how to do this! :)
var discountAmount = 0;
var ogCookie = < %= strJsonCookie % >
for (var i = 0; i < ogCookie.products.length; i++) {
discountAmount = parseFloat(discountAmount) + parseFloat(ogCookie.products[i].discount_amount);
}
alert(discountAmount);
Share
Improve this question
edited Apr 7, 2011 at 14:53
Andy E
345k86 gold badges480 silver badges450 bronze badges
asked Apr 7, 2011 at 14:21
OntonomoOntonomo
5572 gold badges8 silver badges12 bronze badges
5 Answers
Reset to default 8Use parseFloat
instead of parseInt
:
parseFloat("1.19") + parseFloat("2.82") == 4.01
As others have mentioned, you should use parseFloat
instead of parseInt
. However, due to precision issues it's likely you will also need to use .toFixed(2)
when you display the result of the calculation. Using your example, 1.5 + 1.47
may result in 2.9699999999999998
— using .toFixed(2)
will correct this imprecision to 2.97
.
var discountAmount = 0;
var ogCookie = < %= strJsonCookie % >
for (var i = 0; i < ogCookie.products.length; i++) {
discountAmount += parseFloat(ogCookie.products[i].discount_amount);
}
// Output at 2 decimal places
alert(discountAmount.toFixed(2));
Note also that I also optimized your code slightly by removing an unnecessary call to parseFloat
and using the addition assignment operator (+=
).
use 'parsefloat()' to extract the numbers.
Use parseFloat, not parseInt. parseInt will turn everything into an integer.
Also, why are you using what I assume is php to output the same value to javascript several times? Output it once and store it in a variable! This will also let you put the javascript in a separate file and cache it/deliver it via CDN.
1.47 + 1.5 where both numbers are reals does not equal 1.97. Perhaps that is your problem?
Otherwise, what is your question? What is the problem you are having with the above code? Could a jsFiddle demonstrate it?