Alex Rivera | Logout

Why does modulus operator return fractional number in javascript?

Asked 2010-10-19T08:26:04.200
44

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

Edit
Report

1 Answer

20

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 point operations propagate and amplify the round-off error. Store the number as amount of cents instead. Integer can be represented exactly, and 4990 % 10 will return 0.

answered 2010-10-19T08:32:10.073

Your Answer