Search code examples
c#mathdivisioninteger-division

How can I split/divide an integer number multiple times correctly in C#?


Let's say I have 21875 as totalQuantityNumber.

I need to split the totalQuantityNumber on multiple days in a for loop ex. first day 20000 and the second day 1875. Inside my for loop at the end I do a sum of the splitted quantity so I can verify later if the splitting is correct ex. totalSplittedQuantity += splittedQuantity.

At the end of my splitting I verify if the total sum of my splitted products number is the same with the initial planned total products number ex. totalQuantityNumber== totalSplittedQuantity which it should be 21875 == 21875 but I am always off by one number when the number is odd ex. 21875 == 21874. I tried to make the division decimal and round it up at the end but the problem still persists and some of the times the result is over by one as well ex. 21875 == 21876.

This is my division inside the loop: splittedQuantity = splittedDiffDuration * totalQuantityNumber/ totalDuration;

totalDuration and splittedDiffDuration are in minutes ex. totalDuration = 120; splittedDiffDuration = 60;

Basically I loop through each day from a DateTime interval (startDate, endDate) ex. Monday to Tuesday - splitting the quantity for each day for the duration they were planned ex. let's say on Monday its planned 60 minutes to produce X quantity and on Tuesday the same, 60 minutes to produce the rest of the quantity.

I am new to programming and not so good at math. What am I doing wrong with my division?


Solution

  • Regardless of numbers type (integer, decimal, floating point) there will be an error due to rounding or number representation.

    To achieve what you want, you need to calculate the last proportion as the difference between total and the sum of all previous proportions.

    E.g., given this total and this percentage:

    Total: 100
    Day 1: 30%
    Day 2: 17&
    Day 3: 53%

    proportions will be:
    Day 1: 100 * 30% = 30
    Day 2: 100 * 17% = 17
    Day 3: Total - (Day1 + Day2) = 100 - (30 + 17) = 53.

    This, of course, gives you approximate result for the last one, but it's the only way to get this expression to be always true:

    (Day 1 + Day2 + Day3) = Total