8 java format numbers state-machine bigdecimal
我正在寻找一个方法,如果传递的字符串是有效数字(例如"123.55e-9"," - 333,556"),则返回一个布尔值.我不希望只是做:
public boolean isANumber(String s) {
try {
BigDecimal a = new BigDecimal(s);
return true;
} catch (NumberFormatException e) {
return false;
}
}
Run Code Online (Sandbox Code Playgroud)
显然,该函数应使用状态机(DFA)来解析字符串,以确保无效示例不会欺骗它(例如"-21,22.22.2","33-2").你知道这个库是否存在吗?我真的不想自己写,因为这是一个明显的问题,我相信我会重新发明轮子.
谢谢,
缺口
我会避免重新发明这种方法并使用Apache Commons.如果你使用Spring,Struts或许多其他常用的java库,它们通常都包含Apache公共.你会想要commons-lang.jar文件.这是您想要的NumberUtils中的方法:
isNumber[1]
public static boolean isNumber(java.lang.String str)
Checks whether the String 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.
Parameters:
str - the String to check
Returns:
true if the string is a correctly formatted number
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8632 次 |
| 最近记录: |