简体   繁体   English

了解 .NET 中的银行家四舍五入

[英]Understanding Bankers Rounding in .NET

As I understand, the default rounding mode in .NET is "Bankers Rounding", which follows these rules:据我了解,.NET 中的默认舍入模式是“银行家舍入”,它遵循以下规则:

  • If the digit to round by is less than 5, then round down.如果要四舍五入的数字小于 5,则向下舍入。
  • If the digit to round by is equal to 5 then round to the nearest even number.如果要四舍五入的数字等于 5,则四舍五入到最接近的偶数。
  • if the digit to round by is greater than 5 then round up.如果要舍入的数字大于 5,则向上舍入。

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偶数
  • The number to round by is 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.233501.23450到三个位置,它们都将 go 到1.234

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM