Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript division giving wrong answer? [duplicate]

Tags:

javascript

alert(5.30/0.1);

This gives 52.99999999999999 but should be 53. Can anybody tell how and why?

I want to find that a number is divisible by a given number. Note that one of the number may be a float.

like image 790
Rajeev Vyas Avatar asked Aug 30 '26 04:08

Rajeev Vyas


2 Answers

For the same reason that

0.1 * 0.2 //0.020000000000000004

Some decimal numbers can't be represented in IEEE 754, the mathematical representation used by JavaScript. If you want to perform arithmetic with these numbers in your question, it would be better to multiply them until they are whole numbers first, and then divide them.

like image 119
shanet Avatar answered Aug 31 '26 22:08

shanet


Scale the numbers to become whole. Then modulus the result.

alert((5.30*10) % (0.1*10));
like image 25
DickieBoy Avatar answered Aug 31 '26 21:08

DickieBoy