In this post, we are going to see how to format currency in java.
We can format number into Currency by using NumberFormat class.We need to call NumberFormat.getInstance() to get NumberFormat object by passing specified locale.
For example:
Let’s say you want a Format object for UK Locale or US Locale. You can simply use below code:
//get the object of NumberFormat for UK
NumberFormat nfUK=NumberFormat.getCurrencyInstance(Locale.UK);
//get the object of NumberFormat for US
NumberFormat nfUS=NumberFormat.getCurrencyInstance(Locale.US);
Here Locale represents currency for number conversion.
Then we will call NumberFormat’s format method to simply format number into currency.
nfUk.format(num)
Java program for formatting a number into currency
package org.arpit.java2blog;
import java.text.NumberFormat;
import java.util.Currency;
import java.util.Locale;
public class CurrencyMain
{
public static void main(String args[])
{
double num=9876.890;
//call getInstance() to get Currency object
Currency crUK=Currency.getInstance(Locale.UK);
//get the object of NumberFormat
NumberFormat nfUK=NumberFormat.getCurrencyInstance(Locale.UK);
//using the object of NumberFormat, call format method and passing the number as parameter which we want to change
System.out.println(nfUK.format(num)+ " " +crUK.getDisplayName()); //getDisplayName() generates the currency name of the argumented currency code.
NumberFormat nfUS=NumberFormat.getCurrencyInstance(Locale.US);
Currency crUS=Currency.getInstance(Locale.US);
System.out.println(nfUS.format(num)+" "+crUS.getDisplayName());
Currency crFR=Currency.getInstance(Locale.FRANCE);
NumberFormat nfFR=NumberFormat.getCurrencyInstance(Locale.FRANCE);
System.out.println(nfFR.format(num)+" "+crFR.getDisplayName());
}
}
OUTPUT:
£9,876.89 British Pound
$9,876.89 US Dollar
9 876,89 € Euro
$9,876.89 US Dollar
9 876,89 € Euro
That’s all about formatting number in currency in java.