Javascript Modulo (%) behaves strangely

I am trying to calculate (6.6% 1.1). I expect this to be 0, but I get 1.0999999999999996. You can easily reproduce this in the javascript console. I assume this is a mutual rounding error? How do you solve this problem?

+4
source share
3 answers

The operator %acts on non-integer values ​​in a way that is not entirely obvious. In expression

n % d

what JavaScript does is find the largest integer (I will call it qto reflect the specification), which is less than n / d. Then he calculates the product d * q, and the result is the difference n - (d * q).

(I just ignored the sign problem).

: n d , . 17 % 3. 17 / 3 - 5.something, q 5, 17 - (5 * 3) 2.

- , IEEE 754 6.6 / 1.1 6; - , 6. , q, 5 6. , 6 - (5 * 1.1) 6 - 5.5, ( , ) 1.1.

+3

JavaScript IEEE , 6.6 - 6.5999999 ( ?).

(66 % 11)/10

.

+1

As others have noted, you see the effects of rounding off IEEE-754 floating-point numbers. This is not unique to JavaScript:

$ python
>>> 6.6 % 1.1
1.0999999999999992

The way to solve float problems is to use an arbitrary mathematical precision library:

For example, big.js :

x = new Big(6.6)
// Big {s: 1, e: 0, c: Array[2]}
y = new Big(1.1)
// Big {s: 1, e: 0, c: Array[2]}
x.mod(y).toString()
// "0"
0
source

All Articles