3

Possible Duplicate:
Is JavaScript’s Floating-Point Math Broken?

In Javascript,

3 * 0.1 = 0.30000000000000004

I think this is due to the language's number system where 0.3 cannot be accurately represented. But why the following?

0.15 * 2 = 0.3

Similarly,

0.1 + 0.2 = 0.30000000000000004

But

0.15 + 0.15 = 0.3

How's so?

Community
  • 1
  • 1
  • Rounding sometimes does it right, sometimes not. – Bergi Jan 10 '13 at 05:24
  • Here's a good place to learn more about floating point arithmetic: [What Every Computer Scientist Should Know About Floating-Point Arithmetic](http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). The JS interpreter is relying on the underlying libraries and/or floating point hardware of the host to perform floating point arithmetic, which implement the IEEE 754 floating point standard. You can test particular values at an [online IEEE 754 floating point evaluator](http://babbage.cs.qc.cuny.edu/IEEE-754.old/Decimal.html). As you've discovered, some values will have rounding/truncati – ldav1s Jan 10 '13 at 05:02

1 Answers1

4

But why the following?

0.15 * 2 = 0.3

The result isn't exactly 0.3, but it's close enough so that when the least significant digits are rounded off to display the value, it's rounded to 0.3.

The values 0.1 and 0.15 are not exact either, but the error representing 0.1 seems to be larger than for 0.15. When you use the values in calculations, the errors accumulate, and sooner or later they become large enough not to be rounded off when the values are displayed.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
  • can you better explain the rounding logics when it comes to display it? I guess `toFixed` would show the error – Bertuz Jan 03 '21 at 16:09
  • @Bertuz: The number is just rounded to a few digits less than what the data type can represent, which will remove most errors that the limitation of the data type causes. When you see a number like `0.3` displayed, it has first been rounded to something like `0.3000000000000000`, then the trailing zeroes are just omitted. The `toFixed` function can be used to show the exact value, at least in most browsers. I tested that in Chrome, and it will happily show you up to 100 digits. – Guffa Feb 07 '21 at 12:50