Java - Write code to format Money

Requirements

Write code to format Money

Demo

//package com.book2s;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;

import java.util.Currency;

public class Main {
    public static void main(String[] argv) {
        double amount = 42.45678;
        String currency = "US";
        System.out.println(formatMoney(amount, currency));
    }//from  ww  w .jav a  2 s. c  o  m

    public static final String formatMoney(Double amount, String currency) {

        String currencySymbol = Currency.getInstance(currency).getSymbol();

        DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols();
        decimalFormatSymbols.setDecimalSeparator('.');
        decimalFormatSymbols.setGroupingSeparator(',');
        DecimalFormat decimalFormat = new DecimalFormat("#,##0.00",
                decimalFormatSymbols);

        return String.format("%s %s", currencySymbol,
                decimalFormat.format(amount));
    }
}