![]() If the String passes the numeric test, it may still generate a NumberFormatException error when parsed by the methods we mentioned earlier, for example if it is out of range for int or long. The StringUtils.isNumeric() is the StringUtils equivalent of NumberUtils.isDigits(). If the String contains a leading sign or decimal point the method will return false: String string = "25" The NumberUtils.isDigits() method checks if a string contains only Unicode digits. ( "String doesn't contain creatable number.") ( "String contains a creatable number!") Now, we can even use something along the lines of: String string = "0x10AB" With this method we can cover even more numbers, because a valid Java number includes even hexadecimal and octal numbers, scientific notation, as well as numbers marked with a type qualifier. ![]() This method also accepts a String and checks if it's a valid Java number. This code should return: String is numeric! ![]() Now, we don't really even need a convenience helper method, as isParseable() returns a boolean itself: String string = "10" Note that hexadecimal numbers and scientific notations are not considered parsable. This is very good because solutions that involve frequent exception handling should be avoided if possible - this is exactly what this method helps us with. This method accepts a String and checks if it's a parsable number or not, we can be use this method instead of catching an exception when calling one of the methods we mentioned earlier. Let's now take a look at how we can check for numeric values using these methods. We'll be looking at two classes from the Apache Commons library:īoth of which are very similar to their vanilla Java class counterparts, but with an emphasis on null-safe operations (on numbers and strings respectively), meaning we can even define default values for missing ( null) values. It gives us more fine control over core Java classes, in this case, Strings. Check if String is Numeric with Apache CommonsĪpache Commons is one of the most used third-party libraries for expanding the basic Java Framework. On the other hand, if we expect the String to contain a really big number, then we can call the BigInteger(String) constructor, which translates the String representation into a BigInteger. Running this code would result in: Parsing string: "10"
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |