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

例如:

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


当前回答

这是我对这个问题的解决办法。也许有人会有用。

public static bool IsInt(object number, int? decimalPlaces = null)
{
    bool isInt;
    var splinted = number.ToString().Split(',');

    if (splinted.Length == 1)
        isInt = true;
    else
    {
        var charsAfterComma = decimalPlaces != null ? splinted[1].Substring(0, (int) decimalPlaces) : splinted[1];  
        isInt = charsAfterComma.First().ToString() == "0" && charsAfterComma.Replace("0", "") == "";
    }

    return isInt;
}

其他回答

您可以简单地将double类型与相同值的int类型转换进行比较。

double d = 5.0m;

if (d == (int)d)
{
.... 
}

使用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();

试试这个:

number == Convert.ToInt16(number);
static bool IsWholeNumber(double x) 
{
    return Math.Abs(x % 1) < double.Epsilon;
}

这是我对这个问题的解决办法。也许有人会有用。

public static bool IsInt(object number, int? decimalPlaces = null)
{
    bool isInt;
    var splinted = number.ToString().Split(',');

    if (splinted.Length == 1)
        isInt = true;
    else
    {
        var charsAfterComma = decimalPlaces != null ? splinted[1].Substring(0, (int) decimalPlaces) : splinted[1];  
        isInt = charsAfterComma.First().ToString() == "0" && charsAfterComma.Replace("0", "") == "";
    }

    return isInt;
}