How to Check If a String is Valid Number in Java


In this example we will show how to check if a given string is a valid number with parseDouble and parseInteger methods of Double and Integer wrapper classes.

Source Code

public class CheckValidNumber {

    public static void main(String[] args) {
        String[] str = new String[] {"3.14", "3.14x", "512", "512y"};

        for (int i = 0; i < str.length; i++) {
            if (str[i].indexOf(".") > 0) {
                try {
                    /*
                     * To check if the number is valid decimal number,
                     * use method parseDouble(String str) of Double wrapper class.
                     */
                    Double.parseDouble(str[i]);
                    System.out.println(str[i] + " is a valid decimal number");
                } catch (NumberFormatException nme) {
                    System.out.println(str[i] + " is not a valid number");
                }
            } else {
                try {
                    /*
                     * To check if the number is valid decimal number,
                     * use method parseInt(String str) of Integer wrapper class.
                     */
                    Integer.parseInt(str[i]);
                    System.out.println(str[i] + " is a valid integer number");
                } catch (NumberFormatException nme) {
                    System.out.println(str[i] + " is not a valid number");
                }
            }
        }
    }
}

Output:

3.14 is a valid decimal number
3.14x is not a valid number
512 is a valid integer number
512y is not a valid number
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments