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

例如:

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”)输出值。如果没有小数点,我就不写了。


当前回答

有很多方法可以做到这一点。例如:

double d = 5.0;
bool isInt = d == (int)d;

你也可以用模。

double d = 5.0;
bool isInt = d % 1 == 0;

其他回答

.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

试试这个:

number == Convert.ToInt16(number);

使用int。TryParse将产生以下结果:

        var shouldBeInt = 3;

        var shouldntBeInt = 3.1415;

        var iDontWantThisToBeInt = 3.000f;

        Console.WriteLine(int.TryParse(shouldBeInt.ToString(), out int parser)); // true

        Console.WriteLine(int.TryParse(shouldntBeInt.ToString(), out parser)); // false

        Console.WriteLine(int.TryParse(iDontWantThisToBeInt.ToString(), out parser)); // true, even if I don't want this to be int

        Console.WriteLine(int.TryParse("3.1415", out  parser)); // false

        Console.WriteLine(int.TryParse("3.0000", out parser)); // false

        Console.WriteLine(int.TryParse("3", out parser)); // true

        Console.ReadKey();

对于浮点数,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) {
    if (ceil(num) == num && floor(num) == num)
        return true;
    else
        return false;
}

Problemo妨碍塞舌尔。

编辑:Mark Rushakoff撰写。