Check if a number is a double or an int

后端 未结 5 2175
没有蜡笔的小新
没有蜡笔的小新 2021-02-06 11:49

I am trying to beautify a program by displaying 1.2 if it is 1.2 and 1 if it is 1 problem is I have stored the numbers into the arraylist as doubles. How can I check if a Number

5条回答
  •  没有蜡笔的小新
    2021-02-06 12:19

    Well, you can use:

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

    or even:

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

    If the condition is true, i.e. the body of the if statement executes, then the value is an integer. Otherwise, it's not.

    Note that this will view 1.00000000001 as still a double - if these are values which have been computed (and so may just be "very close" to integer values) you may want to add some tolerance. Also note that this will start failing for very large integers, as they can't be exactly represented in double anyway - you may want to consider using BigDecimal instead if you're dealing with a very wide range.

    EDIT: There are better ways of approaching this - using DecimalFormat you should be able to get it to only optionally produce the decimal point. For example:

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

    Output:

    1
    3.5
    123.457
    10
    

提交回复
热议问题