O'Reilly logo

Java I/O by Elliotte Rusty Harold

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required