1

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);
            }
        };
    }
}
Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
pror21
  • 119
  • 12

2 Answers2

1

As mentioned before, use Float#parseFloat(String) but don't forget to replace the commas:

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.

Community
  • 1
  • 1
beatngu13
  • 7,201
  • 6
  • 37
  • 66
0

A string can be parse to float if and only if.

All the chars in the strring are a valid chars in a float number(including decimal representations which is locale dependent)

the best way could be try to parse it forcing the code to throw an exception if something fails...

Float#parseFloat() will do the job in this case..

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97