pror21 pror21 - 3 months ago 20
Java Question

How to check if a string is parsable to float

How can i check if a string can be parsed to a float number?
I tried the

common-lang
NumberUtils
library but sometimes i get wrong returns.

I don't know if that matter but my float numbers use comma seperators.

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);
}
};
}
}

Answer

As mentioned before, use Float#parseFloat(String) but replace the commas before:

try {
    float val = Float.parseFloat(string.replace(',', '.'));
} catch (NumberFormatException e) {
    // Executed iff the string couldn't be parsed.
}

Inspired by this great answer, you can also check out the corresponding Float#valueOf(String) if you prefer a nasty regex.