可能的重复:
在 C# 中:Math.Round(2.5) 结果是 2(而不是 3)!你在开玩笑吧? https://stackoverflow.com/questions/977796/in-c-math-round2-5-result-is-2-instead-of-3-are-you-kidding-me
.Net 圆形错误 https://stackoverflow.com/questions/846911/net-round-bug
我有一个中间值(number.5),我需要指定如何舍入该值(上限值或下限值)。
我理解的行为Math.Round
与MidPointRounding
参数但这并不能解决我的问题:
// To Even
Console.WriteLine(Math.Round(4.4)); // 4
Console.WriteLine(Math.Round(4.5)); // 4
Console.WriteLine(Math.Round(4.6)); // 5
Console.WriteLine(Math.Round(5.5)); // 6
// AwayFromZero
Console.WriteLine(Math.Round(4.4)); // 4
Console.WriteLine(Math.Round(4.5)); // 5
Console.WriteLine(Math.Round(4.6)); // 5
Console.WriteLine(Math.Round(5.5)); // 6
// in one case I need
Console.WriteLine(Math.Round(4.4)); // 4
Console.WriteLine(Math.Round(4.5)); // 4
Console.WriteLine(Math.Round(4.6)); // 5
Console.WriteLine(Math.Round(5.5)); // 5
// another case I need
Console.WriteLine(Math.Round(4.4)); // 4
Console.WriteLine(Math.Round(4.5)); // 5
Console.WriteLine(Math.Round(4.6)); // 5
Console.WriteLine(Math.Round(5.5)); // 6
你有一个超载Math.Round
从中获取枚举值MidpointRounding
.
这有两个选择:
-
至偶数(默认)也称为银行家舍入。将四舍五入到最接近的对。所以 2.5 变成 2,而 3.5 变成 4。
-
远离零:始终将 X.5 向上舍入为 X+1;例如,2.5 变为 3。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)