在c#中,Math.Round(2.5)的结果是2。

应该是3,不是吗?为什么在c#中它是2 ?


当前回答

我有这个问题,我的SQL服务器四舍五入0.5到1,而我的c#应用程序没有。所以你会看到两种不同的结果。

这是一个int/long的实现。这就是Java的舍入方法。

int roundedNumber = (int)Math.Floor(d + 0.5);

这可能也是你能想到的最有效的方法。

如果你想保持双精度并使用十进制精度,那么实际上只是使用基于小数点后多少位的10指数的问题。

public double getRounding(double number, int decimalPoints)
{
    double decimalPowerOfTen = Math.Pow(10, decimalPoints);
    return Math.Floor(number * decimalPowerOfTen + 0.5)/ decimalPowerOfTen;
}

你可以输入一个负的小数点作为小数点,这也很好。

getRounding(239, -2) = 200

其他回答

使用自定义舍入

public int Round(double value)
{
    double decimalpoints = Math.Abs(value - Math.Floor(value));
    if (decimalpoints > 0.5)
        return (int)Math.Round(value);
    else
        return (int)Math.Floor(value);
}

从MSDN:

默认为Math。圆的使用 MidpointRounding.ToEven。大多数人 不熟悉“四舍五入? 甚至“作为替代”,四舍五入 “远离零”更常见 . net默认为 “四舍五入到偶数” 统计上的优势是因为 没有分享的倾向 四舍五入的意思是四舍五入 比它循环的频率稍高 向下(假设数字为 四舍五入往往是积极的。)

http://msdn.microsoft.com/en-us/library/system.math.round.aspx

Silverlight不支持midpointrsurround选项。 下面是Silverlight的一个扩展方法,它添加了midpointrsurround枚举:

public enum MidpointRounding
{
    ToEven,
    AwayFromZero
}

public static class DecimalExtensions
{
    public static decimal Round(this decimal d, MidpointRounding mode)
    {
        return d.Round(0, mode);
    }

    /// <summary>
    /// Rounds using arithmetic (5 rounds up) symmetrical (up is away from zero) rounding
    /// </summary>
    /// <param name="d">A Decimal number to be rounded.</param>
    /// <param name="decimals">The number of significant fractional digits (precision) in the return value.</param>
    /// <returns>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.</returns>
    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;
        }
    }
}

来源:http://anderly.com/2009/08/08/silverlight-midpoint-rounding-solution/

您应该检查MSDN中的Math。轮:

这种方法的行为遵循IEEE标准754,第4节。这种四舍五入有时被称为最接近四舍五入,或银行家四舍五入。

您可以指定Math的行为。使用重载进行四舍五入:

Math.Round(2.5, 0, MidpointRounding.AwayFromZero); // gives 3

Math.Round(2.5, 0, MidpointRounding.ToEven); // gives 2

因为Silverlight不支持midpointrsurround选项,所以你必须自己编写。喜欢的东西:

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;

}

关于如何使用它作为扩展的例子,请参阅文章:.NET和Silverlight圆整