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

匿名 (未验证) 提交于 2019-12-03 03:04:01

问题:

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 return false.

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 return false.

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)...

http://jsfiddle.net/LzZE6/



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!