Friday, December 20, 2013

Currency formatting

Sometimes we need to work with money in our applications. As usual showed simple format using site or user locale. But what to do if we need to format the money amount with multiply currencies for one locale?

I've created simple project to show the formatting logic. You can download it from Git_Repo.

Need to say, not all currencies have a coins, so we have to handle this point.

java.util.Locale contain the information about currensy (delimiters, coins, etc)

DecimalFormat, NumberFormat - used for amount formatting

private String getResult(double amount, Locale siteLocale, Locale quoteLocale) {

    DecimalFormat decimalFormat = (DecimalFormat) NumberFormat.getCurrencyInstance(siteLocale);
    Currency currency = Currency.getInstance(quoteLocale);
    
    //Get the string currency symbol from locale   
    String symbol = currency.getSymbol(quoteLocale);

    DecimalFormatSymbols smb = new DecimalFormatSymbols(quoteLocale);
    smb.setCurrencySymbol(symbol);

    //Set the currency symbol to site locale
    decimalFormat.setDecimalFormatSymbols(smb);
    decimalFormat.getMaximumFractionDigits();
    decimalFormat.getMinimumFractionDigits();

    return decimalFormat.format(amount);
}

And a result:


No comments:

Post a Comment