在C#中将double转换为int [英] Converting a double to an int in C#
问题描述
double score = 8.6; 在我们的代码中,我们需要转换为int。
int i1 = Convert.ToInt32(score);
int i2 =(int)score;
任何人都可以解释为什么 i1!= i2
?
我得到的结果是: i1 = 9
和 i2 = 8
。
因为 Convert.ToInt32
回合:
返回值:舍入为最接近的32位有符号整数。如果值
位于两个整数之间,则返回偶数;
即4.5,转换为4,5.5转换为6。
a href =http://msdn.microsoft.com/en-us/library/yht2cx7b.aspx>截断:
当您从double或float值转换为整数类型时,
值将被截断。
更新:请参阅Jeppe Stig Nielsen在下面的评论,以获得更多的差异(但是如果得分
是一个实数,则不会发生) 。
In our code we have a double that we need to convert to an int.
double score = 8.6;
int i1 = Convert.ToInt32(score);
int i2 = (int)score;
Can anyone explain me why i1 != i2
?
The result that I get is that: i1 = 9
and i2 = 8
.
Because Convert.ToInt32
rounds:
Return Value: rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.
...while the cast truncates:
When you convert from a double or float value to an integral type, the value is truncated.
Update: See Jeppe Stig Nielsen's comment below for additional differences (which however do not come into play if score
is a real number as is the case here).
这篇关于在C#中将double转换为int的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!