Frage

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?

War es hilfreich?

Lösung

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

Andere Tipps

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)
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top