0
Math.Round(35.035, 2, MidpointRounding.ToEven) // returns: 35.03

The above as I understand it should round the number to two decimal places. The number is halfway between two numbers 35.03 and 35.04.

So I specified round to even so as far as I understand it this means the last decimal place should be even so I was expecting it to round to the nearest even being 35.04.

Could someone please explain to me why it's rounding to an odd on the last decimal place?

4

2 回答 2

3

您需要mM当您表示小数时,否则会导致近似错误。

尝试Math.Round(35.035m, 2, MidpointRounding.ToEven)

不同数据类型的后缀

float f = 1.2f;
double d = 1.2d;
uint u = 2u;
long l = 2L;
ulong ul = 2UL;
decimal m = 2m;
于 2013-09-17T10:14:43.033 回答
1

请参阅http://msdn.microsoft.com/en-us/library/f5898377.aspx

在那里您可以找到以下内容:

来电者须知

由于将十进制值表示为浮点数或对浮点值执行算术运算可能导致精度损失,因此在某些情况下,Round(Double, Int32, MidpointRounding) 方法可能不会按照指定的方式舍入中点值通过模式参数。这在以下示例中进行了说明,其中 2.135 舍入为 2.13 而不是 2.14。发生这种情况是因为该方法在内部将值乘以 10 位,并且这种情况下的乘法运算会损失精度。

使用带小数的 Math.Round 作为第一个值可以解决问题,但会增加类型转换的成本。

于 2013-09-17T10:21:34.513 回答