检查一个数字是双精度型还是整型



我试图通过显示1.2来美化程序,如果它是1.2和1,如果它是1问题是我已经将数字存储到数组列表中为双精度。如何检查一个数字是双精度还是整型?

你可以使用:

if (x == Math.floor(x))

甚至:

if (x == (long) x) // Performs truncation in the conversion

如果条件为真,即执行if语句体,则值为整数。否则,它不是。

注意,这会将1.00000000001视为仍然是双精度值——如果这些值是计算过的(因此可能只是"非常接近"整数值),您可能需要添加一些公差。还要注意,对于非常大的整数,这将开始失败,因为它们无论如何都不能用double精确地表示-如果您处理的范围非常大,您可能需要考虑使用BigDecimal来代替。

编辑:有更好的方法来处理这个问题-使用DecimalFormat,您应该能够使它仅可选地产生小数点。例如:

import java.text.*;
public class Test
{
    public static void main(String[] args)
    {
        DecimalFormat df = new DecimalFormat("0.###");
        double[] values = { 1.0, 3.5, 123.4567, 10.0 };
        for (double value : values)
        {
            System.out.println(df.format(value));
        }
    }
}
输出:

1
3.5
123.457
10

另一个简单的&使用模数运算符(%)的直观解

if (x % 1 == 0)  // true: it's an integer, false: it's not an integer

我是c#程序员,所以我在。net中测试了这个。这在Java中也可以工作(除了使用Console类显示输出的行)。

class Program
{
    static void Main(string[] args)
    {
        double[] values = { 1.0, 3.5, 123.4567, 10.0, 1.0000000003 };
        int num = 0;
        for (int i = 0; i < values.Length; i++ )
        {
            num = (int) values[i];
            // compare the difference against a very small number to handle 
            // issues due floating point processor
            if (Math.Abs(values[i] - (double) num) < 0.00000000001)
            {
                Console.WriteLine(num);
            }
            else // print as double
            {
                Console.WriteLine(values[i]);
            }
        }
        Console.Read();
    }
}

也可以使用这种方法,我发现它很有用。

double a = 1.99; 
System.out.println(Math.floor(a) == Math.ceil(a));

您可以使用:

double x=4;
//To check if it is an integer.
return (int)x == x;

最新更新