我注意到 C#/.NET 中存在以下不一致之处。为什么会这样?
Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.04, Math.Round(1.04, 1));
Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.05, Math.Round(1.05, 1));
Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.06, Math.Round(1.06, 1));
Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.14, Math.Round(1.14, 1));
Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.15, Math.Round(1.15, 1));
Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.16, Math.Round(1.16, 1));
Console.WriteLine();
Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.04, Math.Round(1.04, 1, MidpointRounding.AwayFromZero));
Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.05, Math.Round(1.05, 1, MidpointRounding.AwayFromZero));
Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.06, Math.Round(1.06, 1, MidpointRounding.AwayFromZero));
Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.14, Math.Round(1.14, 1, MidpointRounding.AwayFromZero));
Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.15, Math.Round(1.15, 1, MidpointRounding.AwayFromZero));
Console.WriteLine("{0,-4:#.0} | {1,-4:#.0}", 1.16, Math.Round(1.16, 1, MidpointRounding.AwayFromZero));
输出:
1.0 | 1.0
1.1 | 1.0
1.1 | 1.1
1.1 | 1.1
1.2 | 1.2
1.2 | 1.2
1.0 | 1.0
1.1 | 1.1
1.1 | 1.1
1.1 | 1.1
1.2 | 1.2
1.2 | 1.2
似乎默认的字符串格式化行为是使用 MidpointRounding.AwayFromZero 而不是 Math.Round() 的默认 MidpointRounding.ToEven 进行舍入。
最佳答案
作为历史记录,Format$ 的原始 Visual Basic 实现也与四舍五入不一致,又名 bankers' rounding .原始 Format$ 代码由 Tim Paterson 编写.您可能还记得蒂姆是一个名为 QDOS 的小程序的作者。 (后来称为 MS-DOS)在一段时间内非常畅销。
也许这是 25 年向后兼容性的又一案例。
关于c# - 为什么 .NET 在 String.Format 中使用与默认 Math.Round() 算法不一致的舍入算法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2226081/