Formatting Numbers

Problem

You need to format numbers.

Solution

Use a NumberFormat subclass.

There are several reasons why Java doesn’t provide the traditional printf / scanffunctions from the C programming language. First, these depend on variable-length argument lists, which makes strict type checking impossible. Second and more importantly, they mix together formatting and input/output in a very inflexible way. Programs using printf / scanf can be very hard to internationalize, for example.

JDK 1.1 introduced a new package, java.text , which is full of formatting routines as general and flexible as anything you might imagine. As with printf, there is an involved formatting language, described in the Javadoc page. Consider the presentation of long numbers. In North America, the number one thousand twenty-four and a quarter is written 1,024.25, in most of Europe it is 1 024.25, and in some other part of the world it might be written 1.024,25. Not to mention how currencies and percentages get formatted! Trying to keep track of this yourself would drive the average small software shop around the bend rather quickly.

Fortunately, the java.text package includes a Locale class, and, furthermore, the Java runtime automatically sets a default Locale object based on the user’s environment; e.g., on the Macintosh and MS-Windows, the user’s preferences; on Unix, the user’s environment variables. (To provide a non-default locale, see Section 14.9.) To provide formatters customized ...

Get Java Cookbook 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.