我有以下代码:
int a = Convert.ToInt32(4.5m);
int b = Convert.ToInt32(5.5m);
Console.WriteLine(a);
Console.WriteLine(b);
这是输出结果:
4
6
为什么 Convert.ToInt32 会将小数四舍五入到最接近的偶数?我有以下代码:
int a = Convert.ToInt32(4.5m);
int b = Convert.ToInt32(5.5m);
Console.WriteLine(a);
Console.WriteLine(b);
这是输出结果:
4
6
为什么 Convert.ToInt32 会将小数四舍五入到最接近的偶数?Convert方法使用四舍五入或银行家舍入法:
此方法的行为遵循IEEE标准754第4节。这种舍入有时称为四舍五入或银行家舍入,它最小化由于始终将中间值向单个方向舍入而导致的舍入误差。
若要控制Round方法使用的舍入类型,请调用Math.Round(Double, MidpointRounding)重载。
int a = (int)Math.Floor(4.5m);
int b = (int)Math.Floor(5.5m);
MSDN:
或者:
int a = decimal.ToInt32(4.5m);
int b = decimal.ToInt32(4.5m)
您也可以使用显式的 int 强制类型转换操作符:
int a = (int) 4.5m;
int b = (int) 5.5m;
但请阅读来自MSDN的注意事项:
该运算符支持将一个Decimal类型转换为Int32类型。这种显式转换的语法因语言而异,不同的语言编译器可以提供不同的实现并返回不同的结果。该示例演示了通过使用C#和Visual Basic显式转换Decimal值为Int32值时返回不同的结果。为执行独立于语言的转换,您可以调用ToInt32或Convert.ToInt32(Decimal)方法。
Math.Floor Method (Decimal)
返回不大于指定十进制数的最大整数。
请注意,十进制数比int
更大,因此如果该值大于int.MaxValue
,则会引发OverflowException
异常。
Math.Round()允许您进行选择
Console.WriteLine(Math.Round(4.5m, 0, MidpointRounding.ToEven)); //4
Console.WriteLine(Math.Round(5.5m, 0, MidpointRounding.ToEven)); //6
Console.WriteLine(Math.Round(4.5m, 0, MidpointRounding.AwayFromZero)); //5
Console.WriteLine(Math.Round(5.5m, 0, MidpointRounding.AwayFromZero)); //6
ToEven
)Math.Floor
这样的方法。Math.Round
文档说明了原因:Convert.ToInt32(decimal)
默认执行与Math.Round
相同类型的四舍五入。 - Botz3000我昨天读到了一些关于四舍五入的内容,它会将数字四舍五入到最接近的偶数,这被称为银行家舍入。你必须告诉它你想要如何舍入。
编辑:你要求解释为什么它会舍入到最接近的偶数。
假设你有10个数字(这是一个极端的例子)
1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5
总和 = 60
如果你先将它们四舍五入
总和 = 65,因为它们都会向上取整
如果你使用银行家舍入法
总和 = 60
来自http://msdn.microsoft.com/en-us/library/93kx4xke
返回值
类型:System.Int32 值,四舍五入为最接近的 32 位有符号整数。如果值恰好处于两个整数之间,则返回偶数;也就是说,4.5 转换为 4,5.5 转换为 6。
Botz3000
已经说过的话。我不明白这个回答的意义。 - Security Hound