Damien
Damien

Reputation: 4319

Using toFixed(2) in JavaScript is producing undesired results

I'm doing this:

var refundAmount = parseFloat($('#refundAmount2').val().replace('$',''));
var refundReceived = $('#refundReceived');
var remainderAmount = refundAmount-parseFloat(refundReceived.val().replace('$',''));

alert(parseInt(remainderAmount).toFixed(2));

No matter what I do, the result always ends with 2 decimal places being '.00'. So if the first number is 200.12 and the second is 100.08, it should be alerting me with 100.04 but instead I get 100.00.

Why might this be happening?

Upvotes: 2

Views: 16563

Answers (2)

Antony
Antony

Reputation: 15106

You used parseInt to convert that number to an integer and then used toFixed(2) to convert it to a number with 2 decimal places. Adding 2 decimal places to an integer will always result in .00.

Try

alert(remainderAmount.toFixed(2));

See DEMO.

Upvotes: 7

djs
djs

Reputation: 230

You're getting it as an int with parseInt(), then doing the toFixed(). So you're putting decimal places on an int.

Upvotes: 1

Related Questions