How to use DecimalFormat in Java

By | December 13, 2014

The DecimalFormat class in Java is used to format numbers based on the pattern you specify yourself. This post explains how to use the DecimalFormat class to format different types of numbers.

Basic usage

The DecimalFormat is initialized with a formatting pattern.

String pattern = "###,###.##";
DecimalFormat decimalFormat = new DecimalFormat(pattern);

String format = decimalFormat.format(123456.789);
System.out.println(format);

The output will be 123,456.79.

Syntax

  • 0 is a digit that always displays, even if number has less digits (then 0 is displayed)
  • # is a digit that will not display if the leadings are zeroes
  • . marks the decimal separator
  • , marks the grouping separator (e.g. thousand separator)
  • E marks separation of mantissa and exponent for exponential formats.
  • ; separates formats
  • - marks the negative number prefix
  • % multiplies by 100 and shows number as percentage
  • ? multiplies by 1000 and shows number as per mille value
  • ¤ (\u00A4) is the currency sign – replaced by the currency sign for the Locale. Also makes formatting use the monetary decimal * separator instead of normal decimal separator. ¤¤ makes formatting use international monetary symbols.
  • X marks a character to be used in number prefix or suffix
  • ' marks a quote around special characters in prefix or suffix of formatted number.

Examples

  • ###.### 123.456 → 123.456
  • ###.# 123.456 → 123.5
  • ###,###.## 123456.789 → 123,456.79
  • 000.### 9.95 → 009.95
  • ##0.### 0.95 → 0.95

Leave a Reply

Your email address will not be published. Required fields are marked *