Ontonomo
Ontonomo

Reputation: 557

How do I add to dollar amounts in Javascript

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);

Upvotes: 3

Views: 10709

Answers (5)

Andy E
Andy E

Reputation: 344783

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 (+=).

Upvotes: 8

Reporter
Reporter

Reputation: 3948

use 'parsefloat()' to extract the numbers.

Upvotes: 1

Marcin
Marcin

Reputation: 49886

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?

Upvotes: -2

schizodactyl
schizodactyl

Reputation: 1455

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.

Upvotes: 0

Edwin V.
Edwin V.

Reputation: 1377

Use parseFloat instead of parseInt:

 parseFloat("1.19") + parseFloat("2.82") == 4.01

Upvotes: 8

Related Questions