3

I have multiple calculations which have troubles because of floating math problem in js. I'm trying to fix it by multiplying all parts of equation by 1000 and then dividing the result by 1000.

var a = 16924.83,
    b = 16835.61;

var c = a-b; //outputs 89.22000000000116
var d = (1000*a-1000*b)/1000;  //outputs 89.22 and seems to be working correct

Is it ok to do correction of floating math problem this way?

I did read Is floating point math broken?

Community
  • 1
  • 1
Prosto Trader
  • 3,471
  • 3
  • 31
  • 52
  • 1
    Why not just round the result to the desired number of decimal places... – user229044 May 07 '14 at 16:18
  • 1
    Work in hundredths and scale for display at the very end. – Raymond Chen May 07 '14 at 16:23
  • Related: [Precise Financial Calculation in JavaScript. What Are the Gotchas?](http://stackoverflow.com/questions/2876536/precise-financial-calculation-in-javascript-what-are-the-gotchas) – user247702 May 07 '14 at 16:23
  • This might work, but it's always possible that some combinations of numbers will fail. If these are monetary values you're working with I'd recommend you store and work in integers (i.e. multiply them by 100 and fix to zero decimal places), then divide by 100 and fix again for display. –  May 07 '14 at 16:28

1 Answers1

1

You should round after multiplying:

var d = (Math.round(1000*a)-Math.round(1000*b))/1000;

Just multiplying may not solve the problem. When you assign

var a = 16924.83;

it might internally represent this as something like 16924.8300001, so when you multiply by 1000 you get 16924830.001. You need to round to get rid of that fraction.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Can I round Math.round(1000*a - 1000*b)/1000 - it's just takes less coding, but I don't know if there will be difference. Suppose not? – Prosto Trader May 07 '14 at 16:28
  • I think that will work as long as you don't add/subtract more than 5 variables inside the `Math.round`. Rounding each variable works more generally. – Barmar May 07 '14 at 16:31