Tutorial :c# - rounding time values down to the nearest quarter hour



Question:

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.


Solution:1

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


Solution: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  


Solution:3

How about (x / 15) * 15?


Solution: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;      }  }  


Solution:5

You can use integer division -

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


Solution:6

This is where the modulus operator comes in really handy

number - (number % 15)  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »