什么是检查双是在C#中的一个整数的好办法? [英] What's a good way to check if a double is an integer in C#?

查看:161
本文介绍了什么是检查双是在C#中的一个整数的好办法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能重复:
  <一href="http://stackoverflow.com/questions/2751593/how-to-determine-if-a-decimal-double-is-an-integer">How以确定是否一个小数/双为整数?中

我有double类型的变量,我想检查它是否是一个整数。

目前,我有

 公共BOOL CheckIfInteger(双号)
{
    返回number.ToString()包含==假的。(。);
}
 

有没有更好的办法?

更新:对不起,我没有意识到混淆的可能性,通过整我的意思是整数的数学definiton,那是自然数与非零自然数的底片

解决方案

 返回Math.Truncate(号码)==号;
 

正如在评论中,你可能需要考虑到这样一个事实:重新您的一些presentation可能不是一个准确的整数。在这种情况下,你需要允许一些保证金-的错误:

 双差异= Math.Abs​​(Math.Truncate(编号) - 数字);
收益率(DIFF&LT; 0.0000001)|| (DIFF&GT; 0.9999999);
 

Possible Duplicate:
How to determine if a decimal/double is an integer?

I have a variable of type double and am wanting to check whether it is an integer.

At the moment I have

public bool CheckIfInteger(double number)
{
    return number.ToString().Contains(".") == false;
}

Is there a better way?

UPDATE: Sorry I didn't realise the potential for confusion, by integer I meant the mathematical definiton of integer, that is the natural numbers together with the negatives of the non-zero natural numbers.

解决方案

return Math.Truncate(number) == number;

As mentioned in the comments, you might need to take account of the fact that a double representation of your number might not be an exact integer. In that case you'll need to allow for some margin-of-error:

double diff = Math.Abs(Math.Truncate(number) - number);
return (diff < 0.0000001) || (diff > 0.9999999);

这篇关于什么是检查双是在C#中的一个整数的好办法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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