Search code examples
javascriptfloating-point

Weird Javascript Behaviour: Floating Point Addition giving the wrong answer


Possible Duplicate:
Is JavaScript’s math broken?

This seems really stupid, but when running this, it will display

7.300000000000001 instead of 7.3

<script language="javascript">
    function buttonClicked() {
        var mySum = 1.1 + 1.1 + 1.1 + 0 + 4;
        alert(mySum);
    }
</script>

What would cause this? I have the javascript on a pretty basic aspx page. We are actually using javascript to add up values from form inputs, this was just an example with numbers that were breaking it, there are many others..

Any idea what could be doing this?!?


Solution

  • It has to do with how decimal values are converted to binary floating point numbers. 1/10 turns into a repeating decimal in binary, so the number is not perfectly represented, and repeated operations can expose the error.

    JavaScript uses IEEE-754 floating point numbers, for the record. Some other languages have the same problem.

    How to deal with it? In your case, maybe toPrecision().