Skip to content
Advertisement

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?

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement