Why does modulus operator return fractional number in javascript?

Edgar picture Edgar · Oct 19, 2010 · Viewed 32.3k times · Source

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

Answer

Aaron Digulla picture Aaron Digulla · Oct 19, 2010

Because JavaScript uses floating point math which can lead 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.