Number Formats

To print a formatted number in Java, perform these two steps:

  1. Format the number as a string.

  2. Print the string.

Simple, right? Of course, this is a little like the old recipe for rabbit stew:

  1. Catch a rabbit.

  2. Boil rabbit in pot with vegetables and spices.

Obviously, step 1 is the tricky part. Fortunately, formatting numbers as strings is somewhat easier than catching a rabbit. The key class that formats numbers as strings is java.text.NumberFormat. This is an abstract subclass of java.text.Format. Concrete subclasses such as java.text.DecimalFormat implement formatting policies for particular kinds of numbers.

public abstract class NumberFormat extends Format implements Cloneable

The static NumberFormat.getAvailableLocales() method returns a list of all locales installed that provide number formats. (There may be a few locales installed that only provide date or text formats, not number formats.)

public static Locale[] getAvailableLocales()

You can request a NumberFormat object for the default locale of the host computer or for one of the specified locales in Table 16.1 using the static NumberFormat.getInstance() method. For example:

NumberFormat myFormat = NumberFormat.getInstance();
NumberFormat canadaFormat = NumberFormat.getInstance(Locale.CANADA);
Locale turkey = new Locale("tr", "");
NumberFormat turkishFormat = NumberFormat.getInstance(turkey);
Locale swissItalian = new Locale("it", "CH");
NumberFormat swissItalianFormat = NumberFormat.getInstance(swissItalian);

The ...

Get Java I/O now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.