0

I have a situation where I need to present a total dollar amount and a breakdown of that total.

The total is calculated as follows, rounded to 2 decimal places:

TotalQuantity * rate / #OfDaysInMonth

So for example:

                       Total $ Amount          Rounded
                       ------------------      -------------
17000 * 12.76919 / 31 = 7002.459032258         7002.46

Later on, I have a breakdown of the total quantity. The total quantity is broken into several individual quantities and calculated as follows, with each item rounded to 2 decimal places:

Quantity1 * rate / #OfDaysInMonth 
Quantity2 * rate / #OfDaysInMonth 
Quantity3 * rate / #OfDaysInMonth
... 
QuantityN * rate / #OfDaysInMonth

For example:

                               $ Amount                 Rounded
                               ------------------       -------------
          600 * 12.76919 / 31 =  247.145612903           247.15
         1000 * 12.76919 / 31 =  411.909354839           411.91
         3000 * 12.76919 / 31 = 1235.728064516          1235.73
        12400 * 12.76919 / 31 = 5107.676000000          5107.68
---------------------------------------------------------------------
Total:  17000                   7002.459032258          7002.47

However, as you can see, the sum of the rounded individual amounts doesn't always add up to the rounded total amount.

Is there a way to make the rounded amounts add up to the rounded total?

I don't have access to the total amount or the total quantity at this point. I can't add up the individual quantities to get the total quantity. Neither can I calculate the rounded individual amounts first and then display the total amount from their sum.

I'm thinking maybe somehow I can manipulate the rounding so as to minimize the round-off errors but I'm not sure if this is the best strategy.

mjortan
  • 1
  • 1
  • 1
    You could accumulate the rounding error as you go - i.e. add the cumulative error before rounding the next entry. – Oliver Charlesworth Apr 09 '17 at 23:55
  • Closely related: [Q&A](http://stackoverflow.com/a/13483486/335858) – Sergey Kalinichenko Apr 09 '17 at 23:55
  • 4
    Why is it an issue? Rounding is a non-linear operator that doesn't distribute over addition. You could fudge some of the roundings for essentially aesthetic purposes, but there is an element of arbitrariness in doing so. – John Coleman Apr 10 '17 at 00:14

0 Answers0