How to check if a string contains only numbers in Java

Sometimes we deal with strings, and we need to determine whether a string is a valid number or not. In this tutorial, we are going to see how to check that a string contains only numbers in Java.

To check if the string contains only numbers, in the try{} block we use the parseFloat() method of the Float class to convert the string to a Float.

If it returns an error, that means the string is not a number.


How to check if a string contains only numbers in Jav:
public class Main {

    public static void main(String[] args) {

        String str = "985.12";
        boolean b = true;

        try {
            Float f = Float.parseFloat(str);
        } catch (NumberFormatException e) {
            b = false;

        if(b == true)
            System.out.println(str+" is a number");
            System.out.println(str+" is not a number");


985.12 is a number
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *