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:
1 2 3 4 5 6 |
//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.
1 2 3 |
nfUk.format(num) |
Java program for formatting a number into currency
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
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.
Was this post helpful?
Let us know if this post was helpful. Feedbacks are monitored on daily basis. Please do provide feedback as that\'s the only way to improve.