0

Consider the following calculation

3 * 20.9

normally it equals to 62.7. However, when I calculate it in javascript, the output is 62.699999999999996. And what's more I found that 7, 11 will also produce the wrong answer. Why it goes wrong and how to make it right? I think it's about the binary?

demo

panda
  • 1,344
  • 3
  • 14
  • 35
  • It's because of the floating point precision. http://stackoverflow.com/questions/1458633/how-to-deal-with-floating-point-number-precision-in-javascript – Steve Buzonas May 27 '15 at 07:36
  • Duplicate question: [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Yogi May 27 '15 at 07:36
  • The imprecision occurs because 0.9 can't be mapped to a finite binary floating point number. You can use libraries such as BigDecimal if this poses a problem for you: https://github.com/dtrebbien/BigDecimal.js/ – Alex May 27 '15 at 07:37

2 Answers2

0

To keep only 1 decimal. Use

(3*20.9).toFixed(1)

Updated Fiddle

Zee
  • 8,420
  • 5
  • 36
  • 58
0

Try this:

Number((3*20.9).toFixed(1));
Radonirina Maminiaina
  • 6,958
  • 4
  • 33
  • 60