I did a coding assignment one of these days that needed me to round a given price to the nearest even cent. Though the requirement was a bit odd, it became interesting when I realized that the built-in rounding methods in .Net were not sufficient.
10.346 has to round to 10.34
10.356 has to round to 10.36
I wrote the following method to implement this:
10.346 has to round to 10.34
10.356 has to round to 10.36
I wrote the following method to implement this:
public static decimal RoundToEvenCents(decimal sourceNumber)
{
var tempNumber = sourceNumber * 100;
var lowerValue = Math.Floor(tempNumber);
var upperValue = Math.Ceiling(tempNumber);
var evenValue = (lowerValue % 2 == 0) ? lowerValue : upperValue;
return evenValue / 100;
}
Though I am not sure if this is a valid business requirement, putting it here just in case somebody needs it.
Comments
Post a Comment