How to parse numbers more strict than what NumberFormat does in Java?

后端 未结 7 1119
醉梦人生
醉梦人生 2021-02-09 01:59

I\'m validating user input from a form.

I parse the input with NumberFormat, but it is evil and allow almost anything. Is there any way to parse number more strict?

7条回答
  •  北海茫月
    2021-02-09 02:11

    Maybe this helps:

    String value = "number_to_be_parsed".trim();
    NumberFormat formatter = NumberFormat.getNumberInstance();
    ParsePosition pos = new ParsePosition(0);
    Number parsed = formatter.parse(value, pos);
    if (pos.getIndex() != value.length() || pos.getErrorIndex() != -1) {
        throw new RuntimeException("my error description");
    }
    

    (Thanks to Strict number parsing at mynetgear.net)

提交回复
热议问题