如何检查字符串是否可以解析为 float ?
我尝试了 common-lang
NumberUtils
库,但有时我得到错误的返回。
我不知道这是否重要,但我的 float 使用逗号分隔符。
public TableCell call(TableColumn param) {
return new TableCell<Course, String>() {
@Override
public void updateItem(String item, boolean empty) {
super.updateItem(item, empty);
if (NumberUtils.isParsable(item)) {
if (NumberUtils.toFloat(item) >= 5) {
this.setTextFill(Color.GREEN);
} else if (NumberUtils.toFloat(item) < 5) {
this.setTextFill(Color.RED);
}
setText(item);
}
};
}
}
最佳答案
如前所述,使用 Float#parseFloat(String)
但不要忘记替换逗号:
try {
float val = Float.parseFloat(string.replace(',', '.'));
} catch (NumberFormatException e) {
// Executed iff the string couldn't be parsed.
}
灵感来自this great answer ,您还可以查看对应的Float#valueOf(String)
如果您更喜欢讨厌的正则表达式。
关于java - 如何检查字符串是否可解析为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39182829/