Currency Formats

If you know you're going to be working with money, you can request a currency formatter with the static NumberFormat.getCurrencyInstance() method:

public static final NumberFormat getCurrencyInstance()
public static NumberFormat getCurrencyInstance(Locale inLocale)

import java.text.*;
import java.util.*;

public class MinimumWage {

  public static void main(String[] args) {
  
    NumberFormat dollarFormat = NumberFormat.getCurrencyInstance(Locale.ENGLISH);
    double minimumWage = 5.15;
    
    System.out.println("The minimum wage is " 
     + dollarFormat.format(minimumWage));
    System.out.println("A worker earning minimum wage and working for forty");
    System.out.println("hours a week, 52 weeks a year, would earn " 
     + dollarFormat.format(40*52*minimumWage));
    
  }

}


Output:
This program prints
The minimum wage is $5.15
A worker earning minimum wage and working for forty 
hours a week, 52 weeks a year, would earn $10,712.00

Notice how nicely the numbers are formatted. Nowhere did I add dollar signs, say that I wanted exactly two numbers after the decimal point, or that I wanted to separate the thousands with commas. The NumberFormat class took care of that. There are limits to how far this goes. Currency formats may change the currency sign in different locales, but they won't convert the values (between U.S. and Canadian dollars or between U.S. dollars and British pounds, for example). Since conversion rates float from day to day and minute to minute that's a bit much to ask of a static class. If you wanted to do this, you need to provide some source of the conversion rate information, either from user input or pulled off the network.
Copyright 2000 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified January 29, 2000