How to Check whether a String is a valid number

0 Flares Twitter 0 Facebook 0 Google+ 0 LinkedIn 0 Filament.io 0 Flares ×

In java, checking whether a String is a valid number is straightforward. It involves trying to convert the String to a number, catch the NumberFormatException and decide appropriately. Hmm. Not so elegant. Let us take some examples to illustrate this.

Check Whether a String is a Double – Example Code

In order to check whether the given string, a double the steps are as follow

  • Convert the String to a double using the Double.parseDouble() method
  • Catch the NumberFormatException
  • If exception, then not a Double
  • If no exception, then it is a Double

 

Check Whether a String is an Integer – Example Code

In order to check whether the given string is an Integer, the steps are as follow

  • Convert the String to an Integer using the Integer.parseInt() method
  • Catch the NumberFormatException
  • If exception, then not an Integer
  • If no exception, then it is an Integer

Output

Invalid number 10.1
Invalid number ABC
Number is 12.0

Another approach is to use regular expressions to check whether the given string is a number.