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

例如:

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类型与相同值的int类型转换进行比较。

double d = 5.0m;

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

其他回答

试试这个:

number == Convert.ToInt16(number);

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

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

你也可以用模。

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

对于浮点数,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)
    public static bool isInteger(decimal n)
    {
        return n - (Int64)n == 0;
    }
bool IsInteger(double num) {
    if (ceil(num) == num && floor(num) == num)
        return true;
    else
        return false;
}

Problemo妨碍塞舌尔。

编辑:Mark Rushakoff撰写。