问题
How can I use "R" for currency when the locale is set to South Africa?
Currently it shows "ZAR" and I need it to show "R" instead.
I have tried:
final Currency curr = Currency.getInstance("ZAR");
final NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.getDefault());
nf.setCurrency(curr);
final String value = nf.format(12345.67);
and then once all this is done, I replaced ZAR with R using.replace();
回答1:
The NumberFormat
class formats the number based on the locale that is passed as a param. If the locale is for South Africa (new Locale("en", "ZA")
) then the number will appear correctly: R 12,345.67
final Currency curr = Currency.getInstance("ZAR");
final NumberFormat nf = NumberFormat.getCurrencyInstance(new Locale("en", "ZA"));
nf.setCurrency(curr);
final String value = nf.format(12345.67);
System.out.println(value);
回答2:
Ok I found a great example that works:
public static SortedMap<Currency, Locale> currencyLocaleMap;
static {
currencyLocaleMap = new TreeMap<Currency, Locale>(new Comparator<Currency>() {
public int compare(Currency c1, Currency c2){
return c1.getCurrencyCode().compareTo(c2.getCurrencyCode());
}
});
for (Locale locale : Locale.getAvailableLocales()) {
try {
Currency currency = Currency.getInstance(locale);
currencyLocaleMap.put(currency, locale);
}catch (Exception e){
}
}
}
public static String getCurrencySymbol(String currencyCode) {
Currency currency = Currency.getInstance(currencyCode);
System.out.println( currencyCode+ ":-" + currency.getSymbol(currencyLocaleMap.get(currency)));
return currency.getSymbol(currencyLocaleMap.get(currency));
}
from here: Not getting currency symbols for specific Locale
回答3:
Build your own NumberFormat
class (that extends Java's), and implement your own version of format
; calling the base class function for all currencies other than ZAR
.
The approach you're currently taking will tend to lead to a lot of repeated (and unencapsulated) code.
来源:https://stackoverflow.com/questions/35337115/use-r-instead-of-zar-for-south-african-currency