This example show you how to change the currency symbol for the defined locale using the DecimalFormatSymbols.setCurrencySymbol()
method. After changing the currency symbol, the DecimalFormatSymbols
instance is passed to the DecimalFormat
object which does the formatting.
package org.kodejava.text;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.util.Locale;
public class CurrencyFormatSymbols {
public static void main(String[] args) {
double number = 123456.789;
Locale[] locales = {
Locale.CANADA, Locale.GERMANY, Locale.UK, Locale.ITALY, Locale.US
};
String[] symbols = {"CAD", "EUR", "GBP", "ITL", "USD"};
for (int i = 0; i < locales.length; i++) {
// Gets currency's formatted value for each locale
// without change the currency symbol
DecimalFormat formatter =
(DecimalFormat) NumberFormat.getCurrencyInstance(locales[i]);
String before = formatter.format(number);
// Create a DecimalFormatSymbols for each locale and sets
// its new currency symbol.
DecimalFormatSymbols symbol = new DecimalFormatSymbols(locales[i]);
symbol.setCurrencySymbol(symbols[i]);
// Set the new DecimalFormatSymbols into formatter object.
formatter.setDecimalFormatSymbols(symbol);
// Gets the formatted value
String after = formatter.format(number);
System.out.println(locales[i].getDisplayCountry() +
" | before: " + before + " | after: " + after);
}
}
}
Here is are the result of our program:
Canada | before: $123,456.79 | after: CAD123,456.79
Germany | before: 123.456,79 € | after: 123.456,79 EUR
United Kingdom | before: £123,456.79 | after: GBP123,456.79
Italy | before: € 123.456,79 | after: ITL 123.456,79
United States | before: $123,456.79 | after: USD123,456.79