简体   繁体   English

指定小数位数时,Math.Round与MidpointRounding.ToEven的行为是否正确?

[英]When specifying the number of decimals, is the behaviour of Math.Round with MidpointRounding.ToEven correct?

I'm trying to use Math.Round however the results I'm getting are not what I expected. 我正在尝试使用Math.Round但是我得到的结果并不是我所期望的。 I'm finding that it only rounds to even when the following digit is a 5 and cannot have any other digits after that. 我发现只有当下面的数字是5并且之后不能有任何其他数字时,它才会四舍五入。

Assert.AreEqual<double>(4d, Math.Round(4.5));          // Pass
Assert.AreEqual<double>(5d, Math.Round(4.6));          // Pass
Assert.AreEqual<double>(6d, Math.Round(5.5));          // Pass
Assert.AreEqual<double>(4d, Math.Round(4.500001));     // Fail - 5
Assert.AreEqual<double>(4d, Math.Round(4.45));         // Pass
Assert.AreEqual<double>(4.4, Math.Round(4.45, 1));     // Pass
Assert.AreEqual<double>(4.4, Math.Round(4.450001, 1)); // Fail - 4.5 

The behaviour is also the same for Decimal.Round . Decimal.Round的行为也是相同的。

Assert.AreEqual<decimal>(4m, Decimal.Round(4.500001m));      // Fail - 5
Assert.AreEqual<decimal>(4.4m, Decimal.Round(4.450001m, 2)); // Fail - 4.5

Shouldn't rounding only take into account the digit directly following the decimal place you're rounding to, as described in MidpointRounding ? 不应该舍入只考虑正在舍入的小数位后面的数字,如MidpointRounding中所述

A rounding operation takes an original number with an implicit or specified precision; 舍入操作采用隐含或指定精度的原始数字; examines the next digit, which is at that precision plus one; 检查下一个数字,即精度加一; and returns the nearest number with the same precision as the original number. 并返回最接近的数字,其精度与原始数字相同。

The behaviour is correct. 行为是正确的。 You are arguing that 4.50001, 4.51, 4.59, 4.599999999999 should all round down to 4. It is clear that figures over 4.5 are closer to 5 than they are to 4 and therefore should be rounded up to 5. 您认为4.50001,4.51,4.59,4.599999999999应该全部向下舍入到4.显然,4.5以上的数字比4更接近于5,因此应该四舍五入为5。

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

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