by JBrooks
10. November 2011 09:09
In Excel 34.5 will round to 35 and in .NET it will round to 34. This is because .NET defaults to using the MidpointRounding.ToEven mode – also called banker’s rounding. In .NET you have the option of overriding this by passing in the other MidpointRounding like:
Math.Round(34.5, MidpointRounding.AwayFromZero); // Now rounds to 35
A little annoying since in all of the applications that I’ve ever written the users expect rounding to match Excel’s and I’ve never needed the default. Worse, in Silverlight you don’t even have the option to change the default when using Math.Round().
So I had to write my own extension that can be used like:
double myValue = 34.5;
int myRoundedValue = (int) myValue.RoundCorrect(0); // rounds to 35
Here is the extension code:
public static class DoubleExtensions
{
public static double RoundCorrect(this double d, int decimals)
{
double multiplier = Math.Pow(10, decimals);
if (d < 0)
multiplier *= -1;
return Math.Floor((d * multiplier) + 0.5) / multiplier;
}
}
or if you want the code for a normal method it would be
public double RoundCorrect(double d, int decimals)
{
double multiplier = Math.Pow(10, decimals);
if (d < 0)
multiplier *= -1;
return Math.Floor((d * multiplier) + 0.5) / multiplier;
}
6d8e66d2-8f2f-4ddd-910e-8ea3491d751b|0|.0|27604f05-86ad-47ef-9e05-950bb762570c
Tags:
Development | Silverlight