Monday 25 April 2016

Currency Conversion or Formatting As per your needs in Java


How to convert Java String as per Currency Standards of ISO 4217  ?

Solution:

I spent lot of time to get this kind of logic for currencies in java.  I think it will be helpful if any one need to play with currency formats in java.
You can enable grouping and symbols if needed .

/***
*  Used to convert any amount to any currency.
* Ex: 12.3446 to 12.34 for USD
* Ex 10001.12 to 10001 for JPY
*
*/

// you can get currency using java.util.Currency

String convertToCurrency(String actual, Currency curr)
    {
       
        BigDecimal bd  = new BigDecimal(actual);
        NumberFormat nf  = NumberFormat.getCurrencyInstance();
        nf.setCurrency(curr);
        nf.setGroupingUsed(false);
        nf.setMaximumFractionDigits(curr.getDefaultFractionDigits());
        nf.setMinimumFractionDigits(curr.getDefaultFractionDigits());
        DecimalFormat formatter = (DecimalFormat) nf;
        DecimalFormatSymbols symbols = formatter.getDecimalFormatSymbols();
        symbols.setCurrencySymbol(""); // Don't use null.
        formatter.setDecimalFormatSymbols(symbols);
        return formatter.format(bd);
    }

No comments:

Post a Comment

Please comment here