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

例如:

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


当前回答

对于浮点数,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)

其他回答

对于浮点数,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)

Mark Rushakoff的答案可能更简单,但以下也可以,而且可能更有效,因为没有隐式除法运算:

     bool isInteger = (double)((int)f) == f ;

and

     bool isInteger = (decimal)((int)d) == d ;

如果您希望对这两种类型都使用一个表达式,也许可以

     bool isInteger = (double)((int)val) == (double)val ;

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

double d = 5.0m;

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

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

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

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

下面是我的代码,如果字符串“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上对此进行更详细的讨论。