Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an alternative to StringUtils.isNumeric that does what I mean?

StringUtils.isNumeric returns true for "" and false for 7.8. This is of course it's documented behavior, but really not the most convenient for me. Is there something else (ideally in commons.lang) that provides an isActuallyNumeric?

like image 325
Kevin Peterson Avatar asked May 31 '12 00:05

Kevin Peterson


People also ask

What is StringUtils isNumeric for?

isNumeric() is a static method of the StringUtils that is used to check if the given string contains only Unicode digits. Unicode symbols other than Unicode digits are not allowed in the string.

What is not a blank StringUtils?

isNotBlank() is a static method of the StringUtils class that is used to check if a given string is not blank. If a string does not satisfy any of the criteria below, then the string is considered to be not blank. The length of the string is zero or the string is empty. The string points to a null reference.

Is StringUtils contains null safe?

The compare() method in StringUtils class is a null-safe version of the compareTo() method of String class and handles null values by considering a null value less than a non-null value. Two null values are considered equal.

What is StringUtils defaultString?

The defaultString is a static method of the StringUtils class that works as follows: The method takes in two parameters i.e a string and a default string. The default string is returned if the passed string is null . Otherwise, the passed string is returned.


2 Answers

Try isNumber(String) from org.apache.commons.lang.math.NumberUtils.

Checks whether the String [is] a valid Java number.

Valid numbers include hexadecimal marked with the 0x qualifier, scientific notation and numbers marked with a type qualifier (e.g. 123L).

Null and empty String will return false.

UPDATE -

isNumber(String) is now deprecated. Use isCreatable(String) instead.

Thank you eav for pointing it out.

like image 137
JHS Avatar answered Sep 18 '22 13:09

JHS


NumberUtils.isNumber is deprecated.

Your should use

NumberUtils.isCreatable

or

NumberUtils.isParsable

All of them support a decimal point value:

  • NumberUtils.isCreatable support hexadecimal, octal numbers, scientific notation and numbers marked with a type qualifier (e.g. 123L). Not valid octal values will return false (e.g. 09). If you want get its value, you should use NumberUtils.createNumber.
  • NumberUtils.isParsable only support 0~9 and decimal point (.), any other character (e.g. space or other anything) will return false.

By the way, StringUtils.isNumeric's implement has some different between commons-lang and commons-lang3. In commons-lang, StringUtils.isNumeric("") is true. But in commons-lang3, StringUtils.isNumeric("") is false. You can get more info by documents.

like image 21
Cnfn Avatar answered Sep 18 '22 13:09

Cnfn