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

I am checking user input from a form.

I am analyzing the input of NumberFormat , but it is evil and allows almost anything. Is there a way to parse numbers more strictly?

eg. 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()); 
+7
source share
8 answers

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 just want to check and not perform an integer conversion, then regex is another alternative; eg.

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

Perhaps 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 on mynetgear.net )

+6
source

There are many ways to do this:

+3
source

Integer.parseInt(String) will throw a NumberFormatException in all of your examples. I'm not sure if this is what you are looking for, but it is definitely "more stringent."

+2
source

Use DecimalFormat with a format template string.

0
source

Take a look at DecimalFormat, which is a subclass of NumberFormat http://docs.oracle.com/javase/6/docs/api/java/text/DecimalFormat.html

DecimalFormat myFormatter = new DecimalFormat ("###. ###");

0
source

I would not use the java format format, especially with locale settings, if you are worried 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 expect that there will be a problem, but no. test is 2, and pos has an index of 3 and an error index of -1.

0
source

I refused to write my own validation class and went with NEBULA WIDGETS FormattedText

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

0
source

All Articles