Make rounded amounts add up to the calculated total

时间:2017-04-09 23:51:58

标签: algorithm math

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.

0 个答案:

没有答案