Jonas Jonas - 7 months ago 18
Java Question

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

I'm validating user input from a form.

I parse the input with

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

E.g. I would like to not allow these three inputs, for an integer, but
Numberformat
allow all of them:

NumberFormat nf = NumberFormat.getNumberInstance();
nf.setParseIntegerOnly(true);

Number numberA = nf.parse("99.731"); // 99 (not what the user expect)
Number numberB = nf.parse("99s.231"); // 99 (invalid)
Number numberC = nf.parse("9g9"); // 9 (invalid)

System.out.println(numberA.toString());
System.out.println(numberB.toString());
System.out.println(numberC.toString());

Answer

If you want to parse an integer consisting of an optional '-' followed by 1 or more decimal digits, then

int num = Integer.parseInt(str);

or

long num = Long.parseLong(str);

If you simply want to validate and not do the integer conversion, then a regex is another alternative; e.g.

boolean ok = Pattern.compile("-?\\d+").matches(str);