Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Derive Locale from formatted string

Tags:

java

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?


1 Answers

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.

like image 140
Daniel H. Avatar answered Feb 17 '26 22:02

Daniel H.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!