How to check whether input value is integer or float?

130,200

Solution 1

You should check that fractional part of the number is 0. Use

x==Math.ceil(x)

or

x==Math.round(x)

or something like that

Solution 2

How about this. using the modulo operator

if(a%b==0) 
{
    System.out.println("b is a factor of a. i.e. the result of a/b is going to be an integer");
}
else
{
    System.out.println("b is NOT a factor of a");
}

Solution 3

The ceil and floor methods will help you determine if the number is a whole number.

However if you want to determine if the number can be represented by an int value.

if(value == (int) value)

or a long (64-bit integer)

if(value == (long) value)

or can be safely represented by a float without a loss of precision

if(value == (float) value)

BTW: don't use a 32-bit float unless you have to. In 99% of cases a 64-bit double is a better choice.

Solution 4

Math.round() returns the nearest integer to your given input value. If your float already has an integer value the "nearest" integer will be that same value, so all you need to do is check whether Math.round() changes the value or not:

if (value == Math.round(value)) {
  System.out.println("Integer");
} else {
  System.out.println("Not an integer");
}

Solution 5

Also:

(value % 1) == 0

would work!

Share:
130,200
user569125
Author by

user569125

Updated on July 08, 2022

Comments

  • user569125
    user569125 almost 2 years

    How to check whether input value is integer or float?

    Suppose 312/100=3.12 Here i need check whether 3.12 is a float value or integer value, i.e., without any decimal place value.