Use "R" Instead Of "ZAR" For South African Currency
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.getI
Solution 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);
Solution 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));
}
Solution 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.
Post a Comment for "Use "R" Instead Of "ZAR" For South African Currency"