Converting a double to an int in C#(在 C# 中将 double 转换为 int)
问题描述
在我们的代码中,我们需要将 double 转换为 int.
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;
谁能解释一下为什么i1 != i2
?
我得到的结果是:i1 = 9
and i2 = 8
.
The result that I get is that: i1 = 9
and i2 = 8
.
推荐答案
因为 Convert.ToInt32
回合:
Because Convert.ToInt32
rounds:
返回值:四舍五入到最接近的 32 位有符号整数.如果值在两个整数之间,返回偶数;即4.5转4,5.5转6.
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.
...而演员截断:
当您从 double 或 float 值转换为整数类型时,值被截断.
When you convert from a double or float value to an integral type, the value is truncated.
更新:有关其他差异,请参阅下面 Jeppe Stig Nielsen 的评论(但是,如果 score
是实数,就像这里的情况一样,这些差异就不会起作用).
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中将 double 转换为 int


- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- 使用 rss + c# 2022-01-01