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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

5 Comments

+1, You don't have any dollars, just a whole mess of pennies!
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: jsfiddle.net/rGP8Q/2
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.
That's because you're still working with dollars, at least to start with. How I would do it
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.