Why does Math.Round(2.5) return 2 instead of 3?

前端 未结 15 1773
灰色年华
灰色年华 2020-11-22 03:54

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#?

15条回答
  •  既然无缘
    2020-11-22 04:17

    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/

提交回复
热议问题