tags:

views:

47

answers:

2

Consider this script.

<script type="text/javascript">
document.write(parseFloat(parseFloat("97.74")+parseFloat("1.82")) + "<br />");
</script>

Why is the result 99.55999999999999 ? And how can I get the expected output?

+3  A: 

Welcome to floating point numbers :)

You can use .toFixed(numOfDecimalPlaces) for this, for example:

document.write((parseFloat("97.74")+parseFloat("1.82")).toFixed(2) + "<br />");

The output of .toFixed() is a string, rounded to the specified number of decimal places.

Nick Craver
A: 

It's a rounding error, due to the computer working in base 2 whilst your brain works in base 10.

Try this:

var x = parseFloat(parseFloat("97.74")+parseFloat("1.82");
document.write(Math.round(x * 100) / 100);
teedyay