[英]Understanding Bankers Rounding in .NET
As I understand, the default rounding mode in .NET is "Bankers Rounding", which follows these rules:据我了解,.NET 中的默认舍入模式是“银行家舍入”,它遵循以下规则:
We can demonstrate this with the following example:我们可以用下面的例子来证明这一点:
double[] values = {1.14, 1.15, 1.16, 1.24, 1.25, 1.26};
foreach (double value in values)
{
Console.WriteLine(Math.Round(value, 1));
}
// 1.1 (1.14: round down)
// 1.2 (1.15: round to even)
// 1.2 (1.16: round up)
// 1.2 (1.24: round down)
// 1.2 (1.25: round to even)
// 1.3 (1.26: round up)
Then I tried this:然后我尝试了这个:
double value = 1.23456;
Console.WriteLine(Math.Round(value, 3));
// 1.235
My expectation was that this would result in 1.234
by the following logic:我的期望是,这将通过以下逻辑产生
1.234
:
1.234
is even 1.234
是偶数5
, therefore it should round towards even.5
,因此它应该向偶数四舍五入。 So, why does this produce 1.235
?那么,为什么这会产生
1.235
?
I think your misunderstanding is where you say " If the digit to round by is... " when it's really all the digits, all the quantity after that which is being rounded.我认为您的误解是您说“如果要四舍五入的数字是... ”,而实际上是所有数字,四舍五入之后的所有数量。
In 1.23456
you are rounding .00056
which is greater than 0.0005
so it rounds up.在
1.23456
中,您正在舍入大于0.0005
的.00056
,因此它向上舍入。
Banker's rounding only applies at exactly the halfway, to break the tie.银行家的四舍五入仅适用于中途,以打破平局。 Round
1.23350
or 1.23450
to three places and they will both go to 1.234
.将
1.23350
或1.23450
到三个位置,它们都将 go 到1.234
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.