Ive been looking for a proper rounding mechanism but nothing I find seems to be exactly what I need.
I need to round up and round down seperately and I also need to acco
Another approach avoiding arithmetic using type long
.
Using integer division, where a & b are positive integers:
a/b // rounding down
(a+b-1)/b // rounding up
((2*a)+b)/(2*b) // rounding to the nearest (0.5 up)
To round up:
public static DateTime UpToNearestXmin( DateTime dt, int block )
{
int a = dt.Minute;
int b = block;
int mins = block * (( a + b - 1 ) / b );
return new DateTime( dt.Year, dt.Month, dt.Day, dt.Hour, 0, 0 ).AddMinutes( mins );
}
To round down or to nearest, change the mins calculation as appropriate.
The minutes are rounded. The seconds & milliseconds are zeroed which is expected behaviour.