Math.Round() 似乎不一致
代码:
var d1 = Math.Round(187.5); // 188
var d2 = Math.Round(62.5); // 62
为什么会这样呢?
Possible Duplicate:
.Net Round Bug
In C#: Math.Round(2.5) result is 2 (instead of 3)! Are you kidding me?
Code:
var d1 = Math.Round(187.5); // 188
var d2 = Math.Round(62.5); // 62
Why is it so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
默认情况下,
Math.Round
使用一种名为银行家舍入< /a>,当输入介于两个整数之间时,四舍五入到最接近的偶数整数。请参阅 为什么 .NET 使用银行家舍入作为默认值? 了解对这个设计决策的理解。
如果您不喜欢这种行为,可以随时使用此重载Math.Round 的 >,它允许您指定
MidPointRoundingMode
(ToEven、AwayFromZero)。By default,
Math.Round
uses a form of rounding called Banker's Rounding, which rounds to the nearest even integer when the input is halfway between two integers.See Why does .NET use banker's rounding as default? for an understanding of this design decision.
If you don't like this behaviour, you can always use this overload of
Math.Round
, which lets you specify theMidPointRoundingMode
(ToEven, AwayFromZero).您可以通过调用该方法的此重载来更改此行为 - http:// msdn.microsoft.com/en-us/library/ms131274.aspx
You can change this behaviour with an call to this overload of the method - http://msdn.microsoft.com/en-us/library/ms131274.aspx