Home > other >  How do I round to the nearest 0.5
How do I round to the nearest 0.5

Time:06-23

I need increments as follows:

input rounded
10.00 10.50
10.10 10.50
10.20 10.50
10.30 10.50
10.40 10.50
10.50 10.50
10.60 11.00
10.70 11.00
10.80 11.00
10.90 11.00

How to calculate the result in the easiest way

CodePudding user response:

Here's your data:

var data = new[]
{
    new { input = 10.00, expected = 10.50 },
    new { input = 10.10, expected = 10.50 },
    new { input = 10.20, expected = 10.50 },
    new { input = 10.30, expected = 10.50 },
    new { input = 10.40, expected = 10.50 },
    new { input = 10.50, expected = 10.50 },
    new { input = 10.60, expected = 11.00 },
    new { input = 10.70, expected = 11.00 },
    new { input = 10.80, expected = 11.00 },
    new { input = 10.90, expected = 11.00 },
};

The normal way to round up to the nearest 0.5 is to use Math.Ceiling(input * 2.0) / 2.0).

I would do that this way:

var output =
    data
        .Select(x => new
        {
            x.input,
            x.expected,
            actual = Math.Ceiling(x.input * 2.0) / 2.0
        });

That gives me:

output

I do note that 10 stays as 10 instead of 10.5 as per your requirement. I wonder if you got that requirement wrong since 10.5 doesn't round up?

  •  Tags:  
  • .net
  • Related