Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does modulus operator return fractional number in javascript?

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

like image 565
Edgar Avatar asked Oct 19 '10 08:10

Edgar


People also ask

What is the purpose modulo (%) operator in JavaScript?

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.

Can you do modulus operations with decimal numbers?

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.

Does mod return remainder?

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).

How does mod () work?

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.


1 Answers

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.

like image 100
Aaron Digulla Avatar answered Sep 20 '22 04:09

Aaron Digulla