How to check a string is float or int?

Tags: , ,



I have a string and I know that is only contained a number.

I want to check this number is int or float.

Answer

There are many ways to solve your problem for example you can use try{}catch(){}:

Solution 1

public static void main(String[] args) {
    String str = "5588";
    //check if int
    try{
        Integer.parseInt(str);
    }catch(NumberFormatException e){
        //not int
    }
    //check if float
    try{
        Float.parseFloat(str);
    }catch(NumberFormatException e){
        //not float
    }
}

Solution 2

Or you can use regex [-+]?[0-9]*.?[0-9]+ :

boolean correct = str.matches("[-+]?[0-9]*\.?[0-9]+");

For more details take a look at this Matching Floating Point Numbers with a Regular Expression



Source: stackoverflow