How would you check if a String was a number before parsing it?
Java – How to check if a String is numeric in Java
javanumericstring
Related Topic
- Java – How to read / convert an InputStream into a String in Java
- Javascript – How to make the first letter of a string uppercase in JavaScript
- Javascript – How to replace all occurrences of a string in JavaScript
- Javascript – How to check whether a string contains a substring in JavaScript
- Java – How to split a string in Java
- Java – How to convert a String to an int in Java
- Java – How to create a memory leak in Java
- Java – Why is processing a sorted array faster than processing an unsorted array
Best Answer
This is generally done with a simple user-defined function (i.e. Roll-your-own "isNumeric" function).
Something like:
However, if you're calling this function a lot, and you expect many of the checks to fail due to not being a number then performance of this mechanism will not be great, since you're relying upon exceptions being thrown for each failure, which is a fairly expensive operation.
An alternative approach may be to use a regular expression to check for validity of being a number:
Be careful with the above RegEx mechanism, though, as it will fail if you're using non-Arabic digits (i.e. numerals other than 0 through to 9). This is because the "\d" part of the RegEx will only match [0-9] and effectively isn't internationally numerically aware. (Thanks to OregonGhost for pointing this out!)
Or even another alternative is to use Java's built-in java.text.NumberFormat object to see if, after parsing the string the parser position is at the end of the string. If it is, we can assume the entire string is numeric: