Wednesday, July 16, 2014

Java Currency Detail via Locale and Currency Code

Sometimes, while developing our API's we need to give the currency details while formatting a currency. The details of the currency are like what Symbol to use, did we have a separator, what is the number of decimal places, should we place the symbol before or after the formatted number.

This can easily be achieved by using Java API's rather then storing it in the database. Here is the java code that generates all these details. It would be very much helpful if we want to return this information in the API related to currency.

// Source Code

            Locale locale = new Locale("ja", "JP");
            Currency currency = Currency.getInstance("JPY");
            boolean bPre = false;
            int ndx = -1;
            double price = 12345.67;
           
            DecimalFormatSymbols df = DecimalFormatSymbols.getInstance(locale)  ;
            df.setCurrency(currency);
            NumberFormat nF = NumberFormat.getCurrencyInstance(locale);
            nF.setCurrency(currency);
            System.out.println("CURRENCY SYMBOL   = " + df.getCurrencySymbol());
            System.out.println("DECIMAL SEPARATOR = " + df.getDecimalSeparator());
            System.out.println("GROUP SEPARATOR   = " + df.getGroupingSeparator());
            System.out.println("CURRENCY CODE     = " + df.getInternationalCurrencySymbol());
            System.out.println("DECIMAL PLACE     = " + nF.getMaximumFractionDigits());
            String sLP = ((DecimalFormat) nF).toLocalizedPattern();
            ndx = sLP.indexOf('\u00A4');  // currency sign
           
            if (ndx > 0) {
                bPre = false;
            } else {
                bPre = true;
            }
           
            System.out.println("CURRENCY PLACE BEFORE    = " + bPre);
            System.out.println("FORMATTED CURRENCY: " + nF.format(price));

// Output
//For vi_VN Locale and VND currency code.

CURRENCY SYMBOL   = đ
DECIMAL SEPARATOR = ,
GROUP SEPARATOR   = .
CURRENCY CODE     = VND
DECIMAL PLACE     = 0
CURRENCY PLACE BEFORE    = false
FORMATTER CURRENCY: 12.346 đ

// For India Locale    hi_IN and INR Currency Code
CURRENCY SYMBOL   = रू
DECIMAL SEPARATOR = .
GROUP SEPARATOR   = ,
CURRENCY CODE     = INR
DECIMAL PLACE     = 2
CURRENCY PLACE BEFORE    = trueFORMATTED CURRENCY: रू १२,३४५.६७

// For JAPAN Locale    ja_JP and JPY Currency Code
CURRENCY SYMBOL   =
DECIMAL SEPARATOR = .
GROUP SEPARATOR   = ,
CURRENCY CODE     = JPY
DECIMAL PLACE     = 0
CURRENCY PLACE BEFORE    = true

FORMATTED CURRENCY: 12,346


No comments:

Post a Comment