问题描述
我有double类型的变量,我想检查它是否是一个整数。
目前,我有
公共BOOL CheckIfInteger(双号)
{
返回number.ToString()包含==假的。(。);
}
有没有更好的办法?
更新:对不起,我没有意识到混淆的可能性,通过整我的意思是整数的数学definiton,那是自然数与非零自然数的底片
。 返回Math.Truncate(号码)==号;
正如在评论中,你可能需要考虑到这样一个事实:双
重新您的一些presentation可能不是一个准确的整数。在这种情况下,你需要允许一些保证金-的错误:
双差异= Math.Abs(Math.Truncate(编号) - 数字);
收益率(DIFF< 0.0000001)|| (DIFF> 0.9999999);
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#中的一个整数的好办法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!