In C#, the result of Math.Round(2.5)
is 2.
It is supposed to be 3, isn\'t it? Why is it 2 instead in C#?
Silverlight doesn't support the MidpointRounding option. Here's an extension method for Silverlight that adds the MidpointRounding enum:
public enum MidpointRounding
{
ToEven,
AwayFromZero
}
public static class DecimalExtensions
{
public static decimal Round(this decimal d, MidpointRounding mode)
{
return d.Round(0, mode);
}
///
/// Rounds using arithmetic (5 rounds up) symmetrical (up is away from zero) rounding
///
/// A Decimal number to be rounded.
/// The number of significant fractional digits (precision) in the return value.
/// The number nearest d with precision equal to decimals. If d is halfway between two numbers, then the nearest whole number away from zero is returned.
public static decimal Round(this decimal d, int decimals, MidpointRounding mode)
{
if ( mode == MidpointRounding.ToEven )
{
return decimal.Round(d, decimals);
}
else
{
decimal factor = Convert.ToDecimal(Math.Pow(10, decimals));
int sign = Math.Sign(d);
return Decimal.Truncate(d * factor + 0.5m * sign) / factor;
}
}
}
Source: http://anderly.com/2009/08/08/silverlight-midpoint-rounding-solution/