Javascript increases by 1/8 release

for (var i = 0; i < 10; i += .1) {
}

console.log(i) === 10.09999999999998 

BUT...

for (var i = 0; i < 10; i += 1/8) {
}

console.log(i) === 10

Why is the result an integer in increments of 1/8?

+4
source share
1 answer

Since 1/8 can be represented exactly as a base-2 (binary) fraction, but 0.1 cannot. 1/8 is equal to 2 negative third power, but 0.1 is not equal to 2 whole power. Floating-point values ​​are stored in binary format, so mathematics with integer powers of two are more likely to return exact values ​​than mathematics for non-integer powers of 2.

However, it is better to assume that the floating point operation will not be completely accurate. Different languages ​​and processors can give different results, so do not expect 1/8 summation to work everywhere.

+5

Source: https://habr.com/ru/post/1621961/


All Articles