문제

I tried this expression in both my FireFox and Chrome console:

17.99 * 100;

Expected Result: 1799

Actual Result: 1798.9999999999998

I also tried:

parseInt(17.99 * 100);

Expected Result: 1799

Actual Result: 1798

Why is this happening, and how do I get the expected result?

도움이 되었습니까?

해결책

Floating point arithmetic isn't an exact science. The reason is that in memory, your precision is stored in binary (all powers of two). If it can't be represented by an exact power of two you can get some lost precision.

Your number, 1798.9999999999998 had enough lost precision that it didn't round up in the multiplication.

http://en.wikipedia.org/wiki/IEEE_floating_point

다른 팁

Try this:

Math.round(17.99*100)

As the previous answer explained, multiplying a float number is not exact science; what you can do is to expect a result in a certain precision range. Take a look at Number.prototype.toPrecision().

(17.99*100).toPrecision(4)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top