Checking decimal numbers in a local key in Java

Possible duplicate:
Grouping numbers safely and locally sensitive

How can I check strings containing decimal numbers based on language? NumberFormat.parse allows too much, and Double.parseDouble only works for English. 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 } 
+7
source share
2 answers

Concerning

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

you can use NumberFormat.parse (String source, ParsePosition pos) and check if the position at which it parsed is really the last position of the string.

Also, on issue 4.5.6, you can try to set the grouping setGroupingUsed (boolean newValue) as I think this is the problem caused by '.' The character is a grouping symbol in 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 
+2
source

From your comment above, you can use:

 String input = "3,3"; // or whatever you want boolean isValid = input.matches("^\\d+([.,]\\d+)?$"); double value = Double.parseDouble(input.replaceAll(",", ".")); 

If the delimiter can be anything other than a comma, just add it to the square brackets:

 double value = Double.parseDouble(input.replaceAll("[,]", ".")); 
+1
source

All Articles