How would you check if a String was a number before parsing it?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
You can use
NumberFormat#parse
:This a simple example for this check:
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:
Exceptions are expensive, but in this case the RegEx takes much longer. The code below shows a simple test of two functions -- one using exceptions and one using regex. On my machine the RegEx version is 10 times slower than the exception.
Here was my answer to the problem.
A catch all convenience method which you can use to parse any String with any type of parser:
isParsable(Object parser, String str)
. The parser can be aClass
or anobject
. This will also allows you to use custom parsers you've written and should work for ever scenario, eg:Here's my code complete with method descriptions.
I modified CraigTP's solution to accept scientific notation and both dot and comma as decimal separators as well
example