Reputation:
I'm facing the following problem: From an external service I'm getting formatted number data which can be formatted using different locales:
1.234,00 (de_DE)
1,234.12 (en_US)
What's the best way to programmatically derive the Locale that has been used to format the String so I can parse the value to its primitive type?
Upvotes: 3
Views: 99
Reputation: 1842
One possibility to avoid throwing NumberFormatExceptions is to use regular expressions to detect the locale. From your example:
String sDE = "1.234,00"; // (de_DE)
String sEN = "1,234.12"; // (en_US)
Pattern patternEN = Pattern.compile("[0-9],[0-9].[0-9]");
Pattern patternDE = Pattern.compile("[0-9].[0-9],[0-9]");
System.out.println(" DE - EN : " + patternEN.matcher(sDE).find());
System.out.println(" EN - EN : " + patternEN.matcher(sEN).find());
System.out.println(" DE - DE : " + patternDE.matcher(sDE).find());
System.out.println(" EN - DE : " + patternDE.matcher(sEN).find());
Gives the following result:
DE - EN : false
EN - EN : true
DE - DE : true
EN - DE : false
You may need to refine the regex for a fully working environment.
Upvotes: 1