SPl*_*ten 4 java string-conversion
是否有Java中的内置例程将百分比转换为数字,例如,如果字符串包含100%或100px或100,我想要一个包含100的浮点数.
使用Float.parseInt或Float.valueOf会导致异常.我可以编写一个解析字符串并返回数字的例程,但我问这个已经存在了吗?
eg0*_*t3r 18
我想你可以用:
NumberFormat defaultFormat = NumberFormat.getPercentInstance()
Number value = defaultFormat.parse("100%");
Run Code Online (Sandbox Code Playgroud)
感谢您的帖子和建议,我确实尝试使用eg04lt3r发布的解决方案,但结果已翻译。最后我写了一个简单的函数,它完全满足我的要求。我确信一个好的正则表达式也会起作用。
public static double string2double(String strValue) {
double dblValue = 0;
if ( strValue != null ) {
String strResult = "";
for( int c=0; c<strValue.length(); c++ ) {
char chr = strValue.charAt(c);
if ( !(chr >= '0' && chr <= '9'
|| (c == 0 && (chr == '-' || chr == '+'))
|| (c > 0 && chr == '.')) ) {
break;
}
strResult += chr;
}
dblValue = Double.parseDouble(strResult);
}
return dblValue;
}
Run Code Online (Sandbox Code Playgroud)