我如何告诉如果一个小数或双值是一个整数?

例如:

decimal d = 5.0; // Would be true
decimal f = 5.5; // Would be false

or

double d = 5.0; // Would be true
double f = 5.5; // Would be false

我想知道这一点的原因是,我可以通过编程方式确定我是否想使用. tostring(“N0”)或. tostring(“N2”)输出值。如果没有小数点,我就不写了。


当前回答

.NET 7现在有内置的方法:

小数。IsInteger: https://learn.microsoft.com/en - us/dotnet/api/system.decimal.isinteger?view=net 7.0 翻倍。IsInteger: https://learn.microsoft.com/en - us/dotnet/api/system.double.isinteger?view=net 7.0

你可以在以下地址查看源代码:

https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Decimal.cs https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Double.cs

其他回答

对于浮点数,n % 1 == 0通常是检查小数点后是否有数字的方法。

public static void Main (string[] args)
{
    decimal d = 3.1M;
    Console.WriteLine((d % 1) == 0);
    d = 3.0M;
    Console.WriteLine((d % 1) == 0);
}

输出:

False
True

更新:正如下面@Adrian Lopez提到的,与小值epsilon进行比较将丢弃浮点计算错误。由于这个问题是关于双精度值的,下面将是一个更浮点计算的证明答案:

Math.Abs(d % 1) <= (Double.Epsilon * 100)

也许不是最优雅的解决方案,但如果你不太挑剔,它是有效的!

bool IsInteger(double num) {
    return !num.ToString("0.################").Contains(".");
}
static bool IsWholeNumber(double x) 
{
    return Math.Abs(x % 1) < double.Epsilon;
}

可以对双精度类型使用String格式。这里有一个例子:

double val = 58.6547;
String.Format("{0:0.##}", val);      
//Output: "58.65"

double val = 58.6;
String.Format("{0:0.##}", val);      
//Output: "58.6"

double val = 58.0;
String.Format("{0:0.##}", val);      
//Output: "58"

如果没用就告诉我。

.NET 7现在有内置的方法:

小数。IsInteger: https://learn.microsoft.com/en - us/dotnet/api/system.decimal.isinteger?view=net 7.0 翻倍。IsInteger: https://learn.microsoft.com/en - us/dotnet/api/system.double.isinteger?view=net 7.0

你可以在以下地址查看源代码:

https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Decimal.cs https://github.com/dotnet/runtime/blob/main/src/libraries/System.Private.CoreLib/src/System/Double.cs