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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.