Possible Duplicate:
How to deal with Rounding-off TimeSpan?
Is there a way to easily round a c# TimeSpan (possible containing more than one day) up so that
0 days 23h 59m becomes 1 days 0 h 0 m?
0 days 23h 47m becomes 0 days 23 h 50 m?
etc?
Here's what i've come up with so far:
int remainder = span2.Minutes % 5;
if (remainder != 0)
{
span2 = span2.Add(TimeSpan.FromMinutes(5 - remainder));
}
it seems like a lot of code for something rather simple:( Isn't there some kind of built in c# function I can use to round timespans?
In the C Programming Language, the ceil function returns the smallest integer that is greater than or equal to x (ie: rounds up the nearest integer).
In the C Programming Language, the floor function returns the largest integer that is smaller than or equal to x (ie: rounds downs the nearest integer).
The ceil() function takes a single argument and returns a value of type int . For example: If 2.3 is passed to ceil(), it will return 3. The function is defined in <math. h> header file.
Ceil and Floor functions in C++ In mathematics and computer science, the floor and ceiling functions map a real number to the greatest preceding or the least succeeding integer, respectively. floor(x) : Returns the largest integer that is smaller than or equal to x (i.e : rounds downs the nearest integer).
Here it is:
var ts = new TimeSpan(23, 47, 00);
ts = TimeSpan.FromMinutes(5 * Math.Ceiling(ts.TotalMinutes / 5));
Or with a grain of sugar:
public static class TimeSpanExtensions
{
public static TimeSpan RoundTo(this TimeSpan timeSpan, int n)
{
return TimeSpan.FromMinutes(n * Math.Ceiling(timeSpan.TotalMinutes / n));
}
}
ts = ts.RoundTo(5);
static TimeSpan RoundTimeSpan(TimeSpan value)
{
return TimeSpan.FromMinutes(System.Math.Ceiling(value.TotalMinutes / 5) * 5);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With