Why does 49.90 % 0.10
in JavaScript return 0.09999999999999581
? I expected it to be 0.
The modulo operator is represented by the % character in JavaScript. It returns the remainder of two integers that have been divided. As the remainder will always be less than the divisor, modulo operators can be very useful in restricting the range of outputs.
modulo doesn't work with decimals because it only accepts integers. As discussed above, you can define another procedure to see if two numbers are divisible by each other.
In computing, the modulo operation returns the remainder or signed remainder of a division, after one number is divided by another (called the modulus of the operation).
The modulo operation (abbreviated “mod”, or “%” in many programming languages) is the remainder when dividing. For example, “5 mod 3 = 2” which means 2 is the remainder when you divide 5 by 3.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With