Jonas Jonas - 2 years ago 77
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
allow all of them:

NumberFormat nf = NumberFormat.getNumberInstance();

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)


Answer Source

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

int num = Integer.parseInt(str);


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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download