在 C# 中将 double 转换为 int [英] Converting a double to an int in C#

查看:45
本文介绍了在 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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆