什么是检查双是在C#中的一个整数的好办法?是在、整数、好办法

2023-09-04 22:39:50 作者:网吧告诉我们时间就是金钱

可能重复:   How以确定是否一个小数/双为整数?中

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

目前,我有

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

有没有更好的办法?

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

。 解决方案

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

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

 双差异= Math.Abs​​(Math.Truncate(编号) - 数字);
收益率(DIFF< 0.0000001)|| (DIFF> 0.9999999);
 
javascript根据学生考试成绩,输出其总评的级别

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);