Java – How to Check if a string is a valid number?


This content was proof-read by Grammarly. You can Try Grammary for FREE

Problem statement

You need to check if a input string contain a valid number or not.

Solution

Use the appropriate wrapper class for converting the string to numeric formats. For example Double to convert string to double as shown below.

public class Main {

    public static void main(String[] args) {
        String input = "25";
        try {
            double output = Double.parseDouble(input);
            System.out.println(output);
        }
        catch(NumberFormatException ex)
        {
            System.out.println("This is an invalid number");
        }
    }
}

When the input is a invalid number , the NumberFormatException is caused which needs to be handled by the developers.

%d bloggers like this: