在 C# 中检查 double 是否为整数的好方法是什么?
可能的重复:
如何确定小数/双精度数是否为整数?
我有一个 double 类型的变量,我想检查它是否是整数。
目前我有
public bool CheckIfInteger(double number)
{
return number.ToString().Contains(".") == false;
}
没有更好的办法?
更新:抱歉,我没有意识到可能会造成混淆,我所说的整数是指整数的数学定义,即自然数以及非零自然数的负数。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
正如评论中提到的,您可能需要考虑这样一个事实:数字的双精度表示可能不是精确的整数。在这种情况下,您需要考虑一些误差范围:
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:如果您想检查 Integer,可以这样做:
如果您还想检查该数字是否可以转换为 Int32:
If you want to check for an Integer, this will do it:
If you additionally want to check if the number could be converted into an Int32:
使用字符串表示的陷阱是所使用的区域设置,并且您必须处理舍入问题。大多数情况下0.999999999可以被认为是整数1。以下是考虑舍入误差的小片段:
其中 EPSILON 是一个足够小的双精度值,例如 0.00001
另请参阅此内容以获取更多信息:http://msdn.microsoft.com/en-us/library/system.double.epsilon.aspx
The pitfall of working with string representations is the locale used and yoou have to take care of rounding issues. 0.999999999 can be considered to be integer 1 in most cases. Here is a small snippet taking into account rounding errors:
where EPSILON is a double value that is small enough for your purpose 0.00001 for example
See also this for some more information: http://msdn.microsoft.com/en-us/library/system.double.epsilon.aspx
尝试:
或者更漂亮的:
Try:
Or the prettier:
我会使用 TryParse:
I'd use TryParse:
我认为更好的问题是:如何判断 double 是否足够接近整数以被视为整数?因为否则的话,你一定会遇到歧义。所以我推荐这样的东西:
I think that a better question is: How can I tell if a double is close enough to an integer to be considered an integer for my purposes? Because otherwise, you are bound to run into ambiguities. So I'd recommend something like this:
我喜欢 abatishchev 使用 CurrentCulture 的想法。
这是否不能解决 epsilon 问题(我最初甚至没有考虑过)?
I'm liking abatishchev's idea to use CurrentCulture.
Would this not solve the epsilon problem (which I didn't even consider initially)?
我使用以下字符串扩展方法来检查正则表达式模式
I use the following string extension method which checks against a RegEx pattern