Skip to content Skip to sidebar Skip to footer

Result Of 4.08-1.36 In Console

Possible Duplicate: Is JavaScript’s Math broken? I noticed a weird behavior when I try to run 4.08-1.36 in the Chrome console or Firebug. The console returns 2.719999999999999

Solution 1:

Computers store numbers in binary instead of decimal. Just as you cannot represent the fraction 1/3 exactly in decimal form, you cannot represent the fraction 1/10 exactly in binary, which means there are many values that can be represented exactly in decimal form but not in binary form.

All of the numbers in your example fall into this category. In binary, the decimal number 4.08 becomes 100.00010100011110101110..., where those digits after the binary point repeat forever. The other value, 1.36, becomes 1.01011100001010001111...., and their difference, 2.72, becomes 10.10111000010100011110... in each case, also with an infinitely-repeating binary fraction.

When converting back to decimal for human viewing, the computer rounds to the closest possible match, which isn't always the exact value intended.

Solution 2:

This is because you are dealing with floating point numbers. Whereas an integer value has a set number of possibilities for a given range (i.e. there are exactly 10 values from 0 to 9 inclusive), you end up with an infinite number of possibilities once you start adding decimal point values. In order to be able to store these values in a fixed memory space, computers apply floating point arithmetic which uses approximations that allow a wide range of numbers to be stored in that fixed space of memory. Because of this approximation, you can sometimes end up with seemingly-strange results like yours which are almost, but not exactly, the one you are expecting.

See http://en.wikipedia.org/wiki/Floating_point for more information.

Post a Comment for "Result Of 4.08-1.36 In Console"