# What's the correct way of computing money in programming (precision, repeating decimal) [duplicate]

This is the first time I'll be writing an application (personal) that involves money computation.

One of the potential issues I found is with regards to precision and repeating decimal.

Ex.

``````1 / 3 = 0.333

0.333 * 3 = 0.999
``````

Where'd the 0.001 go?

What's the correct way of doing this operation without losing 0.001 that may add up in the future.

• Anyone who's watched Office Space knows the correct answer is to redirect that 0.001 to your own account :-) en.wikipedia.org/wiki/Salami_slicing Commented Mar 18, 2017 at 3:00
• correct way is to use data structure for this and handle math operations on language level. but not many languages do that. as you discovered you can't use float etc for money - they lie by design...
– rsm
Commented Mar 18, 2017 at 4:52

1. Use the base 10 type that is available in your favorite language or standard library, such as `money` or `decimal`, instead of the `float` or `double` types. Floating point numbers are not suitable for monetary calculations, because they are base 2, not base 10, and so will not always represent money amounts accurately.

2. Use Banker's Rounding when making aggregate computations.

3. Good implementations of base 10 numbers carry additional digits of precision beyond pennies to reduce accuracy loss in your calculations. So if you do all of your calculations and round only the final result to pennies, I think you'll find that you get the right answer.

What would be the point of a division by 3 in your application? I just don't see how that would have a meaning in such an application type.

Anyway, what I suggest is using libraries that allow for aritrary precission numbers, something like these libraries and limiting them to a maximum of let's say 50 decimals in case that periodic numbers where needed, I don't think you'd need more than that.

If you somehow found a number where there's a trailing of nines you could write a function to round to the most near number so something like 4,5849999999...9, would be rounded to 4,585. The possibility of it not being that number in reality are so low that I doubt there would be more than a case in several billions of years, so it looks pretty safe to do it.

• The client asks for his 401(k) contribution to be split equally between three mutual funds? Commented Mar 19, 2017 at 4:22