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

例如:

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


当前回答

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

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

其他回答

bool IsInteger(double num) {
    if (ceil(num) == num && floor(num) == num)
        return true;
    else
        return false;
}

Problemo妨碍塞舌尔。

编辑:Mark Rushakoff撰写。

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

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

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

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

输出:

1
1.02

我遇到过类似的情况,但其中的值是字符串。用户输入的值应该是美元金额,所以我想验证它是数字,并且最多有两位小数点后的数字。

下面是我的代码,如果字符串“s”表示的是一个最多有两位小数的数字,则返回true,否则返回false。它避免了因浮点值不精确而导致的任何问题。

try
{
    // must be numeric value
    double d = double.Parse(s);
    // max of two decimal places
    if (s.IndexOf(".") >= 0)
    {
        if (s.Length > s.IndexOf(".") + 3)
            return false;
    }
    return true;
catch
{
    return false;
}

我将在http://progblog10.blogspot.com/2011/04/determining-whether-numeric-value-has.html上对此进行更详细的讨论。