Skip to content
Advertisement

How to check if a string is ‘float’ or ‘int’

I have a string, and I know that it only contains a number.

How can I check if this number is int or float?

Advertisement

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 Matching Floating Point Numbers with a Regular Expression.

Advertisement