How do I use NumberFormat to format currencies?
Author: Deron Eriksson
Description: This Java tutorial describes how to use NumberFormat to format currencies.
Tutorial created using:
Windows XP || JDK 1.5.0_09 || Eclipse Web Tools Platform 2.0 (Eclipse 3.3.0)
To format a number according to a particular currency, we can call NumberFormat.getCurrencyInstance() to get a format object. Calling format() on this object with our number will format our number according to the currency of the default locale. To format a number for a different currency, we can pass the particular desired locale to NumberFormat.getCurrencyInstance(), which will return a format object for that particular currency. The CurrencyFormatTest class demonstrates formatting a double in US dollars and in Swedish kronor. CurrencyFormatTest.javapackage test; import java.text.NumberFormat; import java.util.Locale; public class CurrencyFormatTest { public static void main(String[] args) throws Exception { double num = 1323.526; NumberFormat defaultFormat = NumberFormat.getCurrencyInstance(); System.out.println("US: " + defaultFormat.format(num)); Locale swedish = new Locale("sv", "SE"); NumberFormat swedishFormat = NumberFormat.getCurrencyInstance(swedish); System.out.println("Swedish: " + swedishFormat.format(num)); } } The output of CurrencyFormatTest is shown here: US: $1,323.53 Swedish: 1 323,53 kr |