Sunday, March 4, 2012

How do I change the currency symbol in Android?


This example show you how to change the currency symbol for the defined locale using theDecimalFormatSymbols.setCurrencySymbol() method. After changing the currency symbol, theDecimalFormatSymbols instance is passed to the DecimalFormat object which does the formatting.

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);
        }
    }
}

Below is the output ...

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

No comments:

Post a Comment