johnlemon
johnlemon

Reputation: 21489

Javascript parseFloat result

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?

Upvotes: 0

Views: 1325

Answers (2)

teedyay
teedyay

Reputation: 23521

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

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630569

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.

Upvotes: 5

Related Questions