[英]In C#, what is the best way to determine if a decimal “is an int”?
I have a variable that is a decimal and i want to determine if it "is an int" 我有一个十进制变量,我想确定它是否“是一个整数”
public bool IsanInt(decimal variable)
so if the variable passed in was 1, i want to return true 因此,如果传入的变量为1,我想返回true
if it was 1.5, it would return false 如果是1.5,它将返回false
.5 would be false .5将是错误的
10 would be true 10将是真的
what is the best way to do this check? 进行此检查的最佳方法是什么?
Here you go: 干得好:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(IsInt(3.0m)); // True
Console.WriteLine(IsInt(3.1m)); // False
}
public static bool IsInt(decimal variable)
{
return ((variable % 1) == 0);
}
}
Basically, that method is all you need. 基本上,该方法就是您所需要的。 I just included the entire console program so that you can see the results. 我只是包括了整个控制台程序,以便您可以看到结果。
EDIT: 编辑:
So, after some brainstorming on the comments below, I found that it's incredibly difficult, if not impossible (I haven't found the way) to find if the value is decimal
or " integer
" if the decimal value being provided at its very high value. 因此,在对以下评论进行了头脑风暴之后,我发现很难找到(如果不是不可能的话)(我还没有找到方法)(如果提供的十进制值很高时)是decimal
还是“ integer
”值。 Decimal holds a higher value than even UInt64
. 小数比UInt64
都具有更高的值。 When you run this line of code: 运行以下代码行时:
Console.WriteLine(Decimal.MaxValue - 0.5m);
Output: 输出:
79228162514264337593543950334
... you will see that it won't print the decimal value after the period. ...您将看到它不会在句点后显示十进制值。 There is a maximum limitation that is forcing the truncation, so you'll never see that 0.5 being part of the that large value. 强制截断有一个最大限制,因此您永远不会看到0.5是该大值的一部分。 My method can't fix that limitation. 我的方法无法解决该限制。 I'm not sure if there's anything that can do that within C# or .NET, but I'm all ears. 我不确定在C#或.NET中是否可以执行此操作,但是我很高兴。
There's a good article on what you can and can't do with decimal
... better than what MSDN provides in my opinion: 有一篇很好的文章介绍了decimal
可以做什么和不能做什么...比我认为MSDN更好:
http://www.dotnetperls.com/decimal http://www.dotnetperls.com/decimal
public bool IsInteger(decimal value)
{
return value == Math.Round(value);
}
怎么样
return Math.Round(n) == n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.