Reputation: 231
I tried a lot.But was unable to find a solution. I have a code for formatting currency. I am using the below code :
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(locale);
Here I am facing an issue. Consider a case with France locale. In my case, locale can be en_FR and fr_FR.
DecimalFormatSymbols decimalFormats = new DecimalFormatSymbols();
decimalFormats.setCurrencySymbol(currencySymbol);
((DecimalFormat) numberFormat).setDecimalFormatSymbols(decimalFormats);
formattedCurrency = numberFormat.format(Double.valueOf(number));
So if the locale is en_FR, the formattedCurrency value will be € 10.00 and if the locale is fr_FR, the value will be 10.00 €.
So I would like to know the role of language code in this calculation methods.Since en_FR has en, I guess it is by default taking as en_US. So currency symbol coming left of price.
I need to get 10.00 € always if the country is France irrespective of language code. Is there are other way to get the currency formatting based on country, rather than locale?
Upvotes: 2
Views: 2916
Reputation: 2516
Just specify the country code , instead of language and country
try to modify like below for you :
String countryCode="FR"; // or use "String countryCode=Locale.getDefault().getCountry();" for system default locale
NumberFormat numberFormat = NumberFormat.getCurrencyInstance(new Locale(countryCode));
Note:
The Locale points to language and not to country specific , above code will work as expected in most scenario where the ISO country code and language code will be the same.
Upvotes: 2
Reputation: 4266
You can simply specify FRANCE
as your Locale
, and it will always print it on the right hand side for you.
String formattedCurrency = DecimalFormat.getCurrencyInstance(Locale.FRANCE).format(10.00);
Output:
10,00 €
Edit:
You can get the user's Locale
:
Locale currentLocale = Locale.getDefault();
And pass that as the parameter:
String formattedCurrency = DecimalFormat.getCurrencyInstance(currentLocale).format(10.00);
I'm not in France, but for me it will print:
€10.00
Which is correct for Ireland.
2nd Edit:
You can get the country name from the currentLocale
above, by getting the display country - but this is stored as a String
String country = currentLocale.getDisplayCountry();
Then convert it to a Locale
to use as a parameter
public static Locale getLocaleFromString(String localeString) {
return new Locale(localeString, "");
}
Note: this method is an edited snippet from here
And use it in your formatter then
Locale l = getLocaleFromString(country);
String number = DecimalFormat.getCurrencyInstance(l).format(10.00);
Upvotes: 0