c# - 为什么 .NET Math.Round 方法在处理负值时四舍五入而不是四舍五入?

标签 c# .net

我注意到,当我调用 Math.Round 并为其提供小数值 -0.375 并尝试将其四舍五入到小数点后两位时,它会将值四舍五入为 -0.38。我一直被教导,5 或更大意味着四舍五入向上,这意味着它应该是 -0.37。四舍五入到 -0.37 是 Javascript 执行此操作的方式,这也是我一开始发现这个问题的方式。

这是一些示例代码。

    decimal negNumber = -0.375m;
    var resultToEven = Math.Round(negNumber, 2, MidpointRounding.ToEven);
    var resultAwayFromZero = Math.Round(negNumber, 2, MidpointRounding.AwayFromZero);
    Console.WriteLine("Original Number: " + negNumber);
    Console.WriteLine("ToEven: " + resultToEven);
    Console.WriteLine("Away from zero: " + resultAwayFromZero);

这是它的输出。

Original Number: -0.375
ToEven: -0.38
Away from zero: -0.38

我正在使用 .NET 4.0。

最佳答案

Math.Round 中的默认行为是使用 MidpointRounding.ToEven ,它“向最接近的偶数”舍入。

MSDN describes why this was chosen :

If the digit in the digits position is odd, it is changed to an even digit. Otherwise, it is left unchanged. This behavior follows IEEE Standard 754, section 4. It is sometimes called rounding to nearest, or banker's rounding. It minimizes rounding errors that result from consistently rounding a midpoint value in a single direction.

您的第二个调用使用 AwayFromZero,它明确舍入:

toward the nearest number that is away from zero

在您的例子中,-0.38 比 -0.37 更远离 0.0。

关于c# - 为什么 .NET Math.Round 方法在处理负值时四舍五入而不是四舍五入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8042331/

相关文章:

c# - 如何解决 "Service not available, closing transmission channel. The server response was: Server busy, too many connections"

.net - 系统.BadImageFormatException : Could not load file or assembly or one of its dependencies

c# - 条码扫描windows phone 8

C# WriteFile(),无法写入 USB HID 设备

c# - WCF 超时异常! mscorlib.dll 中出现类型为 'System.TimeoutException' 的异常

c# - 使用 LINQ Min() 获取对象?

c# - 如何在静态类中覆盖 ToString?

c# - ASP.NET 将 PDF 写入文件系统

c# - 如何在托管函数中 Hook 非托管函数?

c# - 如何将最小起订量与 Xamarin.Forms DependencyService 结合使用