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


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01