Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 NumberFormat, 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());
like image 447
Jonas Avatar asked Dec 07 '11 13:12

Jonas


People also ask

Is NumberFormat thread safe?

text. NumberFormat is not thread safe.

What is NumberFormat in Java?

NumberFormat is the abstract base class for all number formats. This class provides the interface for formatting and parsing numbers. NumberFormat also provides methods for determining which locales have number formats, and what their names are. NumberFormat helps you to format and parse numbers for any locale.

How do you create a NumberFormat object in Java?

To format a number for the current Locale, use one of the factory class methods: myString = NumberFormat. getInstance(). format(myNumber);


1 Answers

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)

like image 179
napu Avatar answered Nov 15 '22 12:11

napu