Java Program to check if a string is a valid number


To check if a string is a valid Integer, use the Integer.parseInt() method, with the string to be checked passed as a parameter.

To check if a string is a valid Float, use the Float.parseFloat() method, with the string to be checked passed as a parameter.

The following is an example that checks for valid integer.

Example

 Live Demo

public class Demo {
   public static void main(String args[]) throws Exception {
      String id = "100";
      int val = Integer.parseInt(id);
      System.out.println(val);
   }
}

Output

100

The following is an example that checks for valid float.

Example

 Live Demo

public class Demo {
   public static void main(String args[]) throws Exception {
      String id = "100.5";
      float val = Float.parseFloat(id);
      System.out.println(val);
   }
}

Output

100.5

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 26-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements