c# - rounding time values down to the nearest quar

2020-08-17 08:00发布

问题:

Does anyone have a good way to round down a number between 0 and 59 to the nearest 15. I'm using C# 3.5.

So ...

  • 1 would be 0
  • 29 would be 15
  • 30 would be 30

etc etc.

Many thanks.

回答1:

x = x - (x % 15) would be a solution that doesn't rely on integer division.



回答2:

As an extension method on the datetime

public static DateTime RoundDown(this DateTime dateTime)
{
    return new DateTime(dateTime.Year, dateTime.Month, 
         dateTime.Day, dateTime.Hour, (dateTime.Minute / 15) * 15, 0);
}

to use

DateTime date = dateTime.Now.RoundDown();//for example


回答3:

How about (x / 15) * 15?



回答4:

I don't know of a library call for this (like .Round(...)), perhaps and extension method would fit nicely?

I would go for a simple IF statement.

If speed is an issue, try an expanded switch statement for each value. Use unit tests to see whats faster if that's an issue.

To be complete...

//...
[TestMethod]
    public void round_down()
    {
        Assert.AreEqual(-5.RoundDown(), 0);
        Assert.AreEqual(0.RoundDown(), 0);
        Assert.AreEqual(1.RoundDown(), 0);
        Assert.AreEqual(20.RoundDown(), 15);
        Assert.AreEqual(42.RoundDown(), 30);
        Assert.AreEqual(48.RoundDown(), 45);
        Assert.AreEqual(59.RoundDown(), 45);
        Assert.AreEqual(90.RoundDown(), 45);
    }

//...

public static class Ext
{
    public static int RoundDown(this int val)
    {
        if (val < 0)
            return 0;
        if (val < 15)
            return 0;
        if (val < 30)
            return 15;
        if (val < 45)
            return 30;
        return 45;
    }
}


回答5:

You can use integer division -

int number = 43;
int newNumber = number / 15;
int rounded = newNumber * 15;


回答6:

This is where the modulus operator comes in really handy

number - (number % 15)


标签: c# rounding