Using toFixed(2) in javascript is producing undesirred results

Damien picture Damien · Apr 17, 2013 · Viewed 15.2k times · Source

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. Any ideas as to why this is happening? Thanks all!

Answer

Antony picture Antony · Apr 17, 2013

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.