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

例如:

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


当前回答

试试这个:

number == Convert.ToInt16(number);

其他回答

虽然提出的解决方案似乎适用于简单的例子,但这样做一般来说是一个坏主意。一个数字可能不是一个精确的整数,但当你试图格式化它时,它足够接近一个整数,你会得到1.000000。如果你做了一个计算,理论上应该是1,但实际上由于舍入误差,给出的数字非常接近但不完全等于1,就会发生这种情况。

相反,首先格式化它,如果你的字符串以一个句点结尾,然后去掉它们。还有一些格式可以自动地去掉后面的零。这可能够你用了。

double d = 1.0002;
Console.WriteLine(d.ToString("0.##"));
d = 1.02;
Console.WriteLine(d.ToString("0.##"));

输出:

1
1.02

这个怎么样?

public static bool IsInteger(double number) {
    return number == Math.Truncate(number);
}

十进制也是一样的代码。

Mark Byers说得很好:这可能不是你真正想要的。如果你真正关心的是一个四舍五入到小数点后两位的数字是否是整数,你可以这样做:

public static bool IsNearlyInteger(double number) {
    return Math.Round(number, 2) == Math.Round(number);
}
static bool IsWholeNumber(double x) 
{
    return Math.Abs(x % 1) < double.Epsilon;
}

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

bool IsInteger(double num) {
    return !num.ToString("0.################").Contains(".");
}

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

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;
}