views:

44

answers:

4

Why does 49.90 % 0.10 in JavaScript return 0.09999999999999581? I expected it to be 0.

EDIT:

Ok, I didn't know all this stuff about floating points. Thanks. My lecturers were slacking, it seems.

+4  A: 

Because JavaScript uses floating point math which always leads to rounding errors.

If you need an exact result with two decimal places, multiply your numbers with 100 before the operation and then divide again afterwards:

var result = ( 4990 % 10 ) / 100;

Round if necessary.

Aaron Digulla
+1 In many financial systems, this is the way currency are handled internally (multiplied by 100) and when rendered, the currency rules are applied.
Mic
+1  A: 

http://en.wikipedia.org/wiki/Modulo_operation Don't be angry modulo is used with integers ^^ So floating values occure some errors.

MatTheCat
+1  A: 

take a look at floating points and its disadvantages - a number like 0.1 can't be saved correctly as floating point, so there will alwas be such problems. take your numbers *10 or *100 and do the calculations with integers instead.

oezi
+4  A: 

Javascript's Number is using "IEEE double-precision" to store the values. They are incapable of storing all decimal numbers exactly. The result is not zero because of round-off error when converting the decimal number to binary.

49.90 = 49.89999999999999857891452848...
 0.10 =  0.10000000000000000555111512...

Thus floor(49.90 / 0.10) is only 498, and the remainder will be 0.09999....


It seems that you are using numbers to store amount of dollars. Don't do this, as floating pointer operation propagates and amplifies the round-off error. Store the number as amount of cents instead. Integer can be represented exactly, and 4990 % 10 will return 0.

KennyTM