检查数字是double还是int

时间:2011-09-04 07:49:35

标签: java double int

我试图美化一个程序,如果它是1.2则显示1.2,如果是1则显示1问题是我将数字存储在arraylist中作为双打。如何检查Number是double还是int?

5 个答案:

答案 0 :(得分:19)

嗯,你可以使用:

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

答案 1 :(得分:3)

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

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

答案 2 :(得分:0)

我是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();
    }
}

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

您可以使用:

double x=4;

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