0

In javascript, when I calculate 0.15*6, I get 0.89999999 instead of 0.9

I understand that this is due to the floating point arithmetic. But how can I avoid such problem and get correct result?

To add the relevance of this question, I will add my use case here.

I am provided with a min, max and step value all can be integer or floating point numbers. The input range min - max is not necessarily in multiple of the step value.

If the range is not a multiple of step, my task is to extend the range by adjusting (increasing) max value.

Example: min = 0, max = 0.85, step = 0.15

Here the range = 0.85 - 0 = 0.85, and this is not multiple of step value 0.15. So I have to extend the max value.

I am using the below formula to get adjusted max value:

max = Math.ceil((max - min) / step) * step + min;

I expect this to give

>> max = Math.ceil((0.85 - 0) / 0.15) * 0.15 + 0
>> max = Math.ceil(5.666666667) * 0.15
>> max = 6 * 0.15

>> max = 0.9 // <--- But, I get 0.8999999999999999 here

Please note that the number of decimal places are not known, therefore rounding is (probably) not an option.

Izhar Aazmi
  • 915
  • 12
  • 25
  • 1
    As to getting a "correct" result: what's your application, that this tiiiiiny inaccuracy matters? If it's finance, you shouldn't be using floating point in the first place; keep everything in fixed-point integers (e.g. as cents). – Thomas Mar 17 '22 at 09:20
  • I don't think this is a duplicate of that issue based on your question's content, but your question's title doesn't match your actual question which is 'how can I avoid such problem and get correct result?'. I would rename this "how can I avoid floating point problems in JavaScript?" – mikemaccana Mar 17 '22 at 09:23
  • 1
    An easy way to avoid this problem is to work with integers instead. This only applies to numbers where you know the amount of decimal numbers up front. A common example is money. € 1 = 100 euro cents. So change the calculations to always use euro cents instead. If something costs € 0,15 and you need 6 of them you would do 15 * 6 to calculate the amount of euro cents. If you need to convert it back to full euros for display purposes you simply divide by 100. – 3limin4t0r Mar 17 '22 at 09:41
  • The correct solution is to use some kind of decimal number library in JavaScript. – Salman A Mar 17 '22 at 16:51

0 Answers0