Format Currency in Java
1. Introduction:
Many a times its required to format currency in java, especially an amount into a currency format based on user’s locale in case the application is being used globally. Say a user from USA would see the amount formatted in USD format along with the symbol, whereas a user from UK would see a GBP(Global British Pound) format along with the symbol.
To format a number to a particular currency, Java provides us an API called NumberFormat, we invoke getCurrencyInstance to get a format object. Calling format() on this object will format the number based on the default locale (which is in US format). To format based on a different currency we shall pass the appropriate locale to the NumberFormat.getCurrencyInstance().
2. Program:
The below code demonstrates the concept explained above.
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 33 34 35 36 37 38 39 40 |
package com.heapcode.java; import java.math.BigDecimal; import java.text.NumberFormat; import java.util.Locale; /** * @author Manjunath * */ public class CurrencyFormatter { public static void main(String[] args) { BigDecimal amount = new BigDecimal(19319.333); /* Format amount in US format which is the default */ NumberFormat defaultFormat = NumberFormat.getCurrencyInstance(); System.out.println("US: " + defaultFormat.format(amount)); /* Format amount in French Currency format*/ Locale france = new Locale("fr", "FR"); NumberFormat franceFormat = NumberFormat.getCurrencyInstance(france); System.out.println("France: " + franceFormat.format(amount)); /* Format amount in Great Britain Currency format*/ Locale britain = new Locale("en", "GB"); NumberFormat britainFormat = NumberFormat.getCurrencyInstance(britain); System.out.println("UK: " + britainFormat.format(amount)); /* Format amount in German Currency format*/ Locale german = new Locale("de", "DE"); NumberFormat germanFormat = NumberFormat.getCurrencyInstance(german); System.out.println("German: " + germanFormat.format(amount)); /* Format amount in Indian Currency format*/ Locale indian = new Locale("en", "IN"); NumberFormat indianFormat = NumberFormat.getCurrencyInstance(indian); System.out.println("Indian: " + indianFormat.format(amount)); } } |
3. Output:
Note: Observe the difference in currency formatting between France and German even though they both have Euro as currency.
hi,
NumberFormat.getCurrencyInstance(new Locale(“en”, “IN”));
is not working for me. COuld you plss help
Dont use Locale for India it will print Correctly in Indian Currency!!!
nice example… saved 30 min
Thank you!