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

后端 未结 7 1137
醉梦人生
醉梦人生 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:07

    Integer.parseInt(String) will throw a NumberFormatException on all of your examples. I'm not sure if that's what you're looking for, but it's definitely "more strict."

    0 讨论(0)
  • 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)

    0 讨论(0)
  • 2021-02-09 02:14

    I wouldn't use java's number format routine, especially with the locale settings if you worry about validation.

        Locale numberLocale = new Locale(“es”,”ES");
        NumberFormat nf = NumberFormat.getInstance(numberLocale);
        ParsePosition pos = new ParsePosition(0);
        Number test = nf.parse("0.2", pos);
    

    You would expect there to be an issue here, but no.. test is equal to 2 and pos has an index of 3 and error index of -1.

    0 讨论(0)
  • 2021-02-09 02:16

    There are many ways to do that:

    • regex - check if it matches("\\d+")
    • with javax.validation - @Digits(fraction=0, integer=5)
    • apache commons IntegerValidator
    0 讨论(0)
  • 2021-02-09 02:22

    I gave up on writing my own validation class, and went with NEBULA WIDGETS FormattedText

    It was written over the SWT widget API, but you can easily adapt the NumberFormatter class

    0 讨论(0)
  • 2021-02-09 02:28

    Use DecimalFormat with a format pattern string.

    0 讨论(0)
提交回复
热议问题