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?
问题:
回答1:
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 returnfalse
.
UPDATE -
isNumber(String)
is now deprecated. Use isCreatable(String)
instead.
Thank you eav for pointing it out.
回答2:
This isn't exactly in commons.lang
, but it will work.
try { double d = Double.parseDouble(string); // string is a number } catch (NumberFormatException e) { // string is not a number }
回答3:
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 returnfalse
.
By the way, StringUtils.isNumberic
's implement has some different between commons-lang and commons-lang3. In commons-lang, StringUtils.isNumberic("") is true
. But in commons-lang3, StringUtils.isNumberic("") is false
. You can get more info by documents.
回答4:
alternatively you can check to see if any character matches a non Digit like this..
if(myStr.replaceAll("^$"," ").matches("[^\\d\\.]"))
then you know there's stuff in there that isn't 0-9 and/or a .
Here's the javascript equivalent (modify the string to experiment)...