Do you always want to round up? Because that will always round up.
What you’re doing is just adding one minus the remainder to your original value, which means you always get an integer, and it’s always the integer that is one larger than the integer part of the original result, as long as that result had a non-zero remainder.
___
As an example, let’s say you have A/B = C + R
Where C is the largest multiple of B that is less than A, and R is A-C.
So far this is just normal division with fractions.
As an example, if
A = 25
B = 4
Then
C = 6
R = 1/4
This is because B * C is 24, which is the largest multiple smaller than A (which is 25), but there’s 1/4 remaining.
How do we deal with that pesky remainder?
Well, if we always want to round up, and get an integer, that means we need to convert R into the smallest positive multiple of B so that R = 1
That way our equation goes from
25/4 = 6 + 1/4 (= 6.25)
To
25/4 = 6 + 4/4 (= 7)
An easy way to do that is to just add the “missing amount” to the left side. Let’s call that M.
We want to go from
25/4 = 6 + 1/4
To
25/4 + M = 6 + 1
Now we just subtract the top from the bottom and we get
M = 3/4
So 25/4 + 3/4 = C rounded up
This is what we need to add to the left side to make it come out as a rounded up integer version of the result.
But wait! Notice that
4 = B and 3 = B – 1
So we could also write
25/4 + (B-1)/B = C rounded up
Or, subbing A and B back in to the first term,
A/B + (B-1)/B = C rounded up
Note that the left side is all divided by B, so
(A + (B-1))/B = C rounded up
Hence, adding the divisor (B) plus one to the dividend (A) gets you the rounded up version.
___
Note again that this formula will always give you the rounded up version, no matter how tiny that remainder is.
Latest Answers