Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating decimal numbers in a locale-sensitive way in Java [duplicate]

Possible Duplicate:
Parsing numbers safely and locale-sensitively

How can I validate strings containing decimal numbers in a locale-sensitive way? NumberFormat.parse allows too much, and Double.parseDouble works only for English locale. Here is what I tried:

public static void main(String[] args) throws ParseException {
    Locale.setDefault(Locale.GERMAN);

    NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault());
    Number parsed = numberFormat.parse("4,5.6dfhf");
    System.out.println("parsed = " + parsed); // prints 4.5 instead of throwing ParseException

    double v = Double.parseDouble("3,3"); // throws NumberFormatException, although correct
}
like image 659
WannaKnow Avatar asked Jan 07 '13 11:01

WannaKnow


1 Answers

In regards of the

Number parsed = numberFormat.parse("4,5.6dfhf");

problem, you could possibly use NumberFormat.parse(String source, ParsePosition pos) and check if the position where it stopped parsing was indeed the last position of the string.

Also, on the 4.5.6 problem, you can try to set grouping off by setGroupingUsed(boolean newValue) as I think it's an issue produced by the '.' character being the grouping character on the locale.

It should be something like

NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.getDefault());
numberFormat.setGroupingUsed(false);
ParsePosition pos;
String nString = "4,5.6dfhf";

Number parsed = numberFormat.parse(nString, pos);
if (pos.getIndex() == nString.length()) // pos is set AFTER the last parsed position
   System.out.println("parsed = " + parsed);
else
   // Wrong
like image 77
Manuel Miranda Avatar answered Oct 20 '22 22:10

Manuel Miranda