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

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

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