blog’s amazing Rotating Header Image

Are there problems with floating point in JavaScript?

JavaScript is a mature language (holding mature issues), though tomorrow I’ve ran into something that’s out of this world:

<script type="text/javascript">
document.write( 0.1 + 0.2 );
document.write( '<br />' );
document.write( 0.1 + 0.2 === 0.3 );
</script>

Guess what?

0.30000000000000004
false

Well, not exactly the result I’ve expected.

However, the issue is absolutely not unknown neither new: many languages (including C) have similar issues due to the approximate representation of floating point numbers in memory (leaving the deep explanation to others).

For the impatient: you’ve got two options here.

First: use the .toFixed() method, for example:

( 0.1 + 0.2 ).toFixed( 2 )

It works fine when you don’t really need the floating point calculations, which is absolutely fine for money calculations for example.

The second option? Well, I should offer a nice GPL JS library which does the trick. The bad news is that I’m not aware of one, so should you find a solution, feel free to post it in the comments!

Bookmark and Share

Leave a Reply