3

I have some JS calculations going on. Since floating point arithmetic often uses close approximations to numbers instead of exact values, if you round these floating point number to fixed precision, you often get slight differences. When you are dealing with dollars, people don't like these slight differences.

My problem is outlined in this jsfiddle: http://jsfiddle.net/rGP8Q/.

Does anyone know how I can do math operations (multiplication and addition) without introducing these rounding errors coming from the floating point approximations?

EDIT

I found this other post which brings up the same problem, and confirms that JS does not have a built in decimal data type: How to deal with floating point number precision in JavaScript?.

you can see if you JS terminal that

626.175.toFixed(2) == 626.17
626.185.toFixed(2) == 626.18
626.195.toFixed(2) == 626.20

which is inconsistent. We need a true decimal data type.

Community
  • 1
  • 1
jeffery_the_wind
  • 17,048
  • 34
  • 98
  • 160

1 Answers1

2

Yes. Always, ALWAYS deal in units of the smallest denomination, and ONLY divide by 100 at the end, for display purposes only.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • 2
    +1, You don't have any dollars, just a whole mess of pennies! – Shaded Jun 11 '12 at 17:30
  • not sure how that answers my question, assume user inputs dollar amounts, you do some calculations and end up with something like what I had in my jsfiddle. 12.30 + 626.175, here: http://jsfiddle.net/rGP8Q/2/ – jeffery_the_wind Jun 11 '12 at 17:41
  • Multiply by 100 and round the result. Although personally I check to see if there's a decimal point followed by two digits, and then just `replace` the `.` out of there. – Niet the Dark Absol Jun 11 '12 at 18:06
  • 1
    That's because you're still working with dollars, at least to start with. [How I would do it](http://jsfiddle.net/rGP8Q/4/) – Niet the Dark Absol Jun 11 '12 at 19:26
  • @Kolink - but you cannot assume that you start with 1230 and 62617.5, because the user is going to input dollars, and not cents. So input will be 12.30 and the 626.175 comes from a calculation from other user input fields where the units are dollars. – jeffery_the_wind Jun 14 '12 at 19:54