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

后端 未结 7 953
挽巷
挽巷 2021-02-09 01:47

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:29

    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.

提交回复
热议问题