Decimal Formats

The java.text package contains a single concrete subclass of NumberFormat, DecimalFormat. The DecimalFormat class provides even more control over how floating point numbers are formatted:

public class DecimalFormat extends NumberFormat

Most number formats are in fact decimal formats. Generally, you can simply cast any number format to a decimal format, like this:

DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance();

At least in theory, you might encounter a nondecimal format. Therefore, you should use instanceof to test whether or not you’ve got a DecimalFormat:

NumberFormat nf = NumberFormat.getCurrencyInstance();
if (nf instanceof DecimalFormat) {
  DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance();
  //...
}

Alternately, you can place the cast and associated operations in a try/catch block that catches ClassCastExceptions:

try {
  DecimalFormat df = (DecimalFormat) NumberFormat.getCurrencyInstance();
  //...
}
catch (ClassCastException e) {System.err.println(e);}

Decimal Format Patterns and Symbols

Every DecimalFormat object has a pattern that describes how numbers are formatted and a list of symbols that describes with which characters they’re formatted. This allows the single DecimalFormat class to be parameterized so that it can handle many different formats for different kinds of numbers in many locales. The pattern is given as an ASCII string. The symbols are provided by a DecimalFormatSymbols object. These are accessed and manipulated ...

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.