9

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?!?

Community
  • 1
  • 1

3 Answers3

8

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().

Nosredna
  • 83,000
  • 15
  • 95
  • 122
  • 2
    For a fixed number of decimal digits, use [toFixed()](https://www.w3schools.com/jsref/jsref_tofixed.asp) instead – matthieu Apr 12 '17 at 06:43
6

Floating points are stored as the numeric portion (mantissa) and the exponent (how many places to move the decimal point). The mantissa portion of loating point numbers are stored as a sum of fractions. They are calculated by adding a series of fractions. The order of the fractions is:

1/2, 1/4, 1/8, 1/16, 1/32, 1/64, 1/128, ... etc

The binary representation is stored as 0s and 1s which indicate yes/no. For example, 001010 would be 0 * 1/2 + 0 * 1/4 + 1 * 1/8 + 0 * 1/16 + 1 * 1/32.

This is a rough example of why floating points cannot be exact. As you add precision (float -> double -> long double) you get more precision to a limit.

The underlying binary data stored is split into two pieces - one for the part that appears before the decimal point, and the other for the part after the decimal. It's an IEEE standard that has been adopted because of the speed at which calculations can be performed (and probably other factors on top).

Check this link for more information: https://en.wikibooks.org/wiki/A-level_Computing/AQA/Paper_2/Fundamentals_of_data_representation/Floating_point_numbers

Kieveli
  • 10,944
  • 6
  • 56
  • 81
  • 1
    Some floating point numbers can be converted exactly between binary and decimal. .125 obviously maps to 0.001. – Nosredna Jun 24 '09 at 16:58
  • And other trivial floats don't convert. I think 3.135 Couldn't convert for me - or something equally simple. – Kieveli Jun 24 '09 at 17:19
1

http://docs.sun.com/source/806-3568/ncg_goldberg.html

What everyone should know about floating point numbers.

clemahieu
  • 1,419
  • 9
  • 9