Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round up to next quarter

Tags:

c#

algorithm

I would like to round a number up to the next quarter (i.e. 2.1 rounds to 2.25). I understand that I can get the nearest quarter by using Math.Round(num * 4) / 4, but I would like to expand on this so that it always rounds up to the next quarter.

So far my only solutions involve using if blocks, but I would like to exhaust the one-liner algorithm approach first to try to keep things simple.

This is technically language independent, but in this case I am using C#.

To be clear, below are examples of what I want:

  • 2.0 stays as 2.0
  • 2.01 - 2.24 round up to 2.25
  • 2.25 stays as 2.25
  • 2.26 - 2.49 round up to 2.5
  • and so on...
like image 292
Tony Avatar asked Dec 11 '22 10:12

Tony


2 Answers

How about something like this?

return Math.Ceiling(x * 4) / 4;

Here's an explanation. Say you wanted to round up to the nearest whole number. That's easy—it's exactly what Math.Ceiling does.

OK, so we already have an algorithm that has the behavior we want. It's just got the wrong constant.

We can get around this by "mapping" our input, thinking of every "quarter" as mapping to a whole (which would rightly represent the multiple of 0.25):

0.25 => 1
0.50 => 2
0.75 => 3
1.00 => 4
1.25 => 5

&c., &c.

The mapping relationship here is straightforward. To go from left to right, multiply by 4. To go from right to left, divide by 4. Notice every value >= 0.25 < 0.5 will map to something between 1 and 2, which is what we want because Math.Ceiling will round up to 2 in this case, which we can then map back to 0.5.

So essentially we map our input to a value that works with the already-implemented algorithm (Math.Ceiling); then we map the result back to the set of values our input came from.

Make sense?

like image 97
Dan Tao Avatar answered Jan 03 '23 01:01

Dan Tao


You can use:

Math.Ceiling(num * 4) / 4.0;
like image 30
Reed Copsey Avatar answered Jan 03 '23 01:01

Reed Copsey