Number Format example


import java.text.*;


public class FormatTest {

  public static void main(String[] args) {

    NumberFormat nf = NumberFormat.getInstance();
    for (double x = Math.PI; x < 100000; x *= 10) {
      String formattedNumber = nf.format(x);
      System.out.println(formattedNumber + "\t" + x);
    }

  }

}

U.S. English system results:
3.141		3.14159265358979
31.415		31.4159265358979
314.159		314.159265358979
3,141.592		3141.5926535897897
31,415.926	31415.926535897896

The formatted numbers don't use a ridiculous number of decimal places, and group the integer part with commas when it becomes large. Of course the exact formatting depends on the default locale. For instance when I changed the locale to French I encountered this result: French results:
3,141		3.14159265358979
31,415		31.4159265358979
314,159		314.159265358979
3 141,592		3141.5926535897897
31 415,926	31415.926535897896
The French locale uses a decimal comma instead of a decimal point, and separates every three digits in the integer part with a space. This may be confusing to an American, but seems perfectly normal to a Parisian. One of the advantage of number formats is that by using the default number format for the system., much of your program is automatically localized. No extra code is required to do the right thing on French systems, on Canadian systems, on Japanese systems, and so on.
Copyright 2000 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified January 29, 2000