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

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

问题描述


可能重复:

如何确定十进制/双精度是否为整数?

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

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

目前我有

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

有更好的方法吗?

更新:对不起,我没有意识到混淆的可能性,整数我的意思是整数的数学定义,也就是自然数以及非零自然数的负数。

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;

如评论中所述,您可能需要考虑到一个 double 表示您的号码可能不是一个确切的整数。在这种情况下,您需要允许一些错误的边缘:

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

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

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