Common strategies to deal with rounding errors in currency-intensive soft?

Max picture Max · May 18, 2010 · Viewed 9.9k times · Source

What is your advice on:

  1. compensation of accumulated error in bulk math operations on collections of Money objects. How is this implemented in your production code for your locale?
  2. theory behind rounding in accountancy.
  3. any literature on topic.

I currently read Fowler. He mentions Money type, it's typcal structure (int, long, BigDecimal), but says nothing on strategies.

Older posts on money-rounding (here, and here) do not provide a details and formality I need.

Thoughts I found in the inet relate to "Round half even" as the best way to balance error.

Thanks for help.

Answer

Unreason picture Unreason · May 19, 2010

There are many rounding issues when recording financial data. First issue is ability to store and retrieve exact decimal numbers

  • most databases offer decimal data type on which you can specify the number of digits before and after decimal point (currencies vary in number of decimal digits, too, I've dealt with currencies with 0, 2, 3 decimal digits)
  • when dealing with this data and you want to avoid any unexpected rounding errors on the application side you can use BCD as generic approach, or you can use integers to represent any fixed decimal notation or mix your own

If this first issue is sorted out then no addition (or substraction) can introduce any rounding errors. Same goes for multiplication by integer.

The second issue, after you are able to store and retrieve data without loss of information, are expected rounding errors due to division (or multiplication by non integer).

For example if your currency format allows 2 decimals and you want to store transaction that records balances a debit of 10 to 3 equal pieces you can only store it like

10.00  
-3.33  
-3.33  
-3.33  

and

-0.01 

(rounding error)

This is expected problem that will occur regardless of the data type storage choice and that needs to be taken care of if you want your accounts to balance. This situation is mainly introduced by division (or by multiplication by non integers that have many significant digits).

One way to deal with this is to verify if your data balances after such operations and recognize the allowed rounding difference as opposed to an error situation.

EDIT: As for references to literature, this one seems interesting and not too long and concerns quite wide audience with interesting scenarios.