20

I want to make multiplication using JavaScript.

Multiplication of 2 and 0.15 is 0.3 but 3 and 0.15 is 0.44999999999999996. I want to get 0.45 such as result. How can I do it with JavaScript?

Afsun Khammadli
  • 2,048
  • 4
  • 18
  • 28
  • 1
    There is no `int` or `float` in JavaScript. Everything is a `double`. That being said, you're looking for [`toFixed()`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Number/toFixed) if you want to convert your value into a string. – Zeta May 17 '13 at 11:44
  • 1
    http://en.wikipedia.org/wiki/Floating_point – Sirko May 17 '13 at 11:44
  • How can I get 0.45 result for multiplication 0.15 and 3? – Afsun Khammadli May 17 '13 at 11:44
  • See this: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Math/round – Henrik Andersson May 17 '13 at 11:44
  • Yup, it is always the JavaScript, which is broken! Floating point are the same in all languages, and they obey the rules in IEEE 754. – Bakudan May 17 '13 at 11:48
  • thanks toFixed() function is that,what I want to do – Afsun Khammadli May 17 '13 at 11:49
  • same if you add `0.15+0.15+0.15 = 0.44999999999999996`, but weird that `3.15*3=9.45` lol – Jaider Sep 29 '22 at 01:45
  • you can multiply by 100 then divided by 100... so `0.15 x 100 = 15`... `15 * 3 = 45`... `45/100 = 0.45` ... but can risk overflow for large numbers – Jaider Sep 29 '22 at 14:08

2 Answers2

22

It's a rounding error. You may want to round your number to a fixed amount of digits, like this:

parseFloat((your_number).toFixed(2));
Simon M
  • 2,931
  • 2
  • 22
  • 37
9

Unfortunately this happens in any language using floating point arithmetic. It's an artifact arising when floating point operations are encoded into binary, operations performed, and decoded from binary to report the answer in a form you'd expect.

Depending on what you want to do with the output, you can call a round()-like function to round to a number of decimal places or compare the output to a value using a (small) number called a tolerance. E.g. two numbers are considered equal if their absolute difference is less than this tolerance.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483