[Java] How To Check if a String is a Valid Number?
If you are someone new to Java and would like to check if a String is a valid number or not, this post will help you get answer to your question.
Below is the coded snippet with explanation for checking out if a string is a valid number. The below mentioned code is written in Java.
In the below mentioned code snippet, i declared an integer called isThisANumber , this integer will be used to save the parsed Integer. Static method parseInt( ) of the Integer class has been used to attempt to convert the string parameter into an Integer. In case if the string is not a valid integer and throws up parsing issues while converting, NumberFormatException is thrown.
int isThisANumber = 0;
try
{
isThisANumber = Integer.parseInt(someStringToTest);
}
catch (NumberFormatException nfe)
{
System.out.println("This string is not a valid number."); //Oops..not a valid int
}
Do stay tuned to Technofriends for more, one of the best ways of doing so is by subscribing to our feeds. You can subscribe to Technofriends feed by clicking here.
Related posts:
- [Java] Program For Printing Limits of Primitive Data Types
- [Java] Reading a Webpage through URL
- How to get free available memory in Java program
- Polymorphism in Java : Part 2
- [How-To] Print Date/Time in a Given Format in Java
What nonsense. Either you don’t know English/mathematics, or you don’t know Java.
If I initialize:
String someStringToTest = “12.345″;
Is 12.345 a number?
What will your code snippet say?
If this is the extent of your competency, perhaps you shouldn’t be dishing out “advice” on programming.
Here you try this,
String someStringToTest = “12.345″;
Double stringToDouble = null;
if ( someStringToTest.matches(“\\d*\\.\\d*”) )
Here you try this,
String someStringToTest = “12.345″;
Double stringToDouble = null;
if ( someStringToTest.matches(”\\d*\\.\\d*”) )
stringToDouble = Double.parseDouble(someStringToTest);
Bala’s snippet is a nice way to do it and definitely makes sense. I do not see why you have to be mean about his English/mathematics.