Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a number is a double or an int

Tags:

java

int

double

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 is a double or int?

like image 424
chuck finley Avatar asked Sep 04 '11 07:09

chuck finley


People also ask

How do you check if a number is an int?

The Number. isInteger() method returns true if a value is an integer of the datatype Number. Otherwise it returns false .

How do you check if a number is a double C++?

Checking if a double (or float) is NaN in C++ To check whether a floating point or double number is NaN (Not a Number) in C++, we can use the isnan() function. The isnan() function is present into the cmath library. This function is introduced in C++ version 11.

How do you check if it is a double in Java?

To check if the string contains numbers only, in the try block, we use Double 's parseDouble() method to convert the string to a Double . If it throws an error (i.e. NumberFormatException error), it means the string isn't a number and numeric is set to false . Else, it's a number.


2 Answers

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
like image 166
Jon Skeet Avatar answered Oct 27 '22 00:10

Jon Skeet


Another simple & intuitive solution using the modulus operator (%)

if (x % 1 == 0)  // true: it's an integer, false: it's not an integer
like image 33
neel Avatar answered Oct 26 '22 22:10

neel