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

例如:

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 isInteger(decimal n)
    {
        return n - (Int64)n == 0;
    }

其他回答

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

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

对于浮点数,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撰写。

这个怎么样?

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

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

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

你也可以用模。

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