Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Java program to check if a string is a valid number
In Java, verifying whether a string is a valid number is a common requirement in various applications. This process ensures that the string can be safely converted to a numerical type without causing runtime exceptions. To validate if a string can be converted to these types, we use the Integer.parseInt() and Float.parseFloat() methods, respectively.
Problem Statement
Given a string that may contain an integer or a float value, write a Java program to check whether it is valid number or not.
Input
"100" //string value
Output
100 // integer value
Check if a string is a valid number for integer values
To check if a string is a valid Integer, use the Integer.parseInt() method, with the string to be checked passed as a parameter.
- Step 1: Use Integer.parseInt() to try converting the string to an integer.
- Step 2: If it throws NumberFormatException, the string is not a valid integer.
Example
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
Check if a string is a valid number for float values
To check if a string is a valid Float, use the Float.parseFloat() method, with the string to be checked passed as a parameter.
- Step 1: Use Float.parseFloat() to try converting the string to a float.
- Step 2: If it throws `NumberFormatException`, the string is not a valid float.
Example
The following is an example that checks for valid float −
public class Demo {
String id = "100.5";
float val = Float.parseFloat(id);
System.out.println(val);
}
}
Output
100.5
Conclusion
We can conclude that by using Integer.parseInt() and Float.parseFloat(), along with exception handling, you can effectively check if a string is a valid number in Java.
