Home  >  Core Java

Java Currency Formatter

By Arvind Rai, September 09, 2021
On this page we will learn to format a currency in Java. The currency is represented by java.util.Currency API. To format the currency, use java.text.NumberFormat API. The NumberFormat is used to format and parse numbers or currency for any locale.
To start with NumberFormat for currency, instantiate it using following methods.
1.
static final NumberFormat getCurrencyInstance() 
Returns a currency format for the current default locale.
2.
static NumberFormat getCurrencyInstance(Locale inLocale) 
Returns a currency format for the specified locale.

Now find the examples to format the currency.



Example-1

package com.concretepage;
import java.math.BigDecimal;
import java.text.NumberFormat;
public class MyApp1 {
  public static void main(String[] args) {
	BigDecimal b = new BigDecimal(225.32);
	NumberFormat formatter1 = NumberFormat.getCurrencyInstance();
	String c = formatter1.format(b);
	System.out.println(c); // $225.32
  }
} 
Output
$225.32 

Example-2

package com.concretepage;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Locale;
public class MyApp2 {
  public static void main(String[] args) {
	BigDecimal b = new BigDecimal(764.46);
	NumberFormat formatter1 = NumberFormat.getCurrencyInstance(Locale.UK);
	String c1 = formatter1.format(b);
	System.out.println(c1); // £764.46
	NumberFormat formatter2 = NumberFormat.getCurrencyInstance(Locale.US);
	String c2 = formatter2.format(b);
	System.out.println(c2); // $764.46
  }
} 
Output
£764.46
$764.46 

Example-3

package com.concretepage;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.Locale;
public class MyApp3 {
  public static void main(String[] args) {
	BigDecimal b = new BigDecimal("215.8768").setScale(4);	
	NumberFormat formatter1 = NumberFormat.getCurrencyInstance(Locale.FRANCE);
	String c1 = formatter1.format(b);
	System.out.println(c1); // 215,88 €
	NumberFormat formatter2 = NumberFormat.getCurrencyInstance(Locale.JAPANESE);
	String c2 = formatter2.format(b);
	System.out.println(c2); // ¤215.88
  }
} 
Output
215,88 €
¤215.88 

Reference

Class NumberFormat
Class Currency
POSTED BY
ARVIND RAI
ARVIND RAI











©2021 concretepage.com | Privacy Policy | Contact Us