Reputation: 3
I need a function that can parse both 1,123.12 and 1.123,12 to 1123.12 There are 3 sources for the numbers I use, 1 will always come in US format, 1 will always come in PT_BR (1.123,12) and the third may come in any format depending on the locale of the device how can I correctly parse all of them?
Edit: I don't know which way the number is formatted, I need a function that can receive any of those formats and parse it correctly. Maybe what I need is a way to test in which format is a string that represents a number. Something that will receive "1.123,12" and say that is "PT_BR" and receive 1,123.12 and say that is "US". But I have no idea how to do this especially how to make something like this wok for any location.
Upvotes: 0
Views: 3515
Reputation: 20885
You can only get the locale of the environment. There ain't exist anything like a locale in the context of a string, it's the exact opposite: the meaning of the string depends on the locale. There are cases where you can guess the number represented by a string (like the ones you posted) but what about 123,456 for example? It's ambiguous, so no library can do this work. Obviously if you impose some constraint (for example the number must have two decimal digits) you will be able to easily write your own parser, but without such a conventions it's simply impossible
Upvotes: 0
Reputation: 146
US:
NumberFormat nf = NumberFormat.getInstance(Locale.US);
Number number = nf.parse("1,123.12");
Brazilian Portuguese:
NumberFormat nf = NumberFormat.getInstance(Locale.forLanguageTag("pt-BR"));
Number number = nf.parse("1.123,12");
Default locale:
NumberFormat nf = NumberFormat.getInstance();
Number number = nf.parse("1123.12");
Upvotes: 3