Java Reference ยท Text, Formatting and Regex
The DecimalFormat class
Reference for java.text.DecimalFormat: pattern symbols 0, #, comma, percent and exponent, rounding modes, parsing, locale symbols and thread-safety warnings.
java.text.DecimalFormat formats numbers according to a pattern you write, such as #,##0.00 or 000 or 0.0%, and parses text back into numbers. It is the tool for exact control: fixed digits, optional digits, grouping, prefixes, suffixes, scientific notation.
The symbols it prints (decimal point, grouping separator, minus sign) come from a DecimalFormatSymbols object. If you do not pass one, the default locale decides, so pass DecimalFormatSymbols.getInstance(Locale.US) (or Locale.ROOT) whenever the output must be predictable.
DecimalFormat df = new DecimalFormat("#,##0.00", DecimalFormatSymbols.getInstance(Locale.US)); df.format(1234567.891); // "1,234,567.89"
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
public class DecimalFormat extends NumberFormat new DecimalFormat(String pattern) new DecimalFormat(String pattern, DecimalFormatSymbols symbols)
Pattern symbols
| Symbol | Meaning |
|---|---|
0 |
a digit that is always shown (padded with a zero) |
# |
a digit that is shown only if needed |
. |
decimal separator position |
, |
grouping separator; the distance to the end of the integer part sets the group size |
E |
scientific notation, followed by 0s for the minimum exponent digits (0.00E0) |
; |
separates the positive pattern from the negative one |
% |
multiply by 100 and show a percent sign |
โฐ |
multiply by 1000 (per mille) |
ยค |
currency sign |
' |
quotes special characters in a prefix or suffix; '' is a literal quote |
| Method | Description |
|---|---|
format(double), format(long), format(Object) |
formats a number; also accepts BigDecimal and BigInteger through format(Object) |
parse(String) |
parses from the start of the text and returns a Long or Double; throws ParseException |
setRoundingMode(RoundingMode) |
default is HALF_EVEN |
setMaximumFractionDigits(int), setMinimumFractionDigits(int), setGroupingUsed(boolean) |
adjust the pattern after creation |
setParseBigDecimal(boolean) |
make parse return BigDecimal |
toPattern(), toLocalizedPattern() |
the pattern in invariant or localized symbols |
Throws: IllegalArgumentException for an invalid pattern; ParseException from parse.
Usage notes
0versus#. Use0for digits that must appear ("000"gives007) and#for digits that may be dropped."0.##"prints2as2but2.5as2.5.- Half-even rounding.
DecimalFormatrounds ties to the nearest even digit, so2.5becomes2and3.5becomes4.String.format("%.0f", 2.5)uses half-up and gives3. CallsetRoundingMode()if you want to match. - Not thread-safe. A
DecimalFormatkeeps mutable state. Create one per call or per thread, or guard it with a lock; never keep it in a sharedstaticfield. - Always give the symbols.
new DecimalFormat("0.00")uses the default locale, so on a German machine the same code prints3,14. - Doubles carry binary error.
format(0.125)is exact, but1.005is stored slightly below 1.005, so the pattern0.00prints1.00(whileString.format("%.2f", 1.005)prints1.01). For money pass aBigDecimal. - Leading zero. With
#.00the integer part is optional, so0.5prints.50; use0.00to keep the zero. - Parsing is lenient.
parse("42 apples")returns42. Useparse(String, ParsePosition)and check that the whole text was consumed if you need strict validation. - Pattern limits. Patterns cannot express a fixed number of integer digits with grouping in arbitrary places; the grouping size is taken from the last comma.
- Percent and per mille change the value, not just the suffix:
0.256with"0.0%"prints25.6%.