Java Reference ยท Text, Formatting and Regex
Java printf and format specifiers
Reference for Java printf, String.format and format specifiers: %d, %s, %f, %x, %e, flags, width, precision, argument indexes and the exceptions they throw.
System.out.printf(), String.format() and String.formatted() all share one mini-language: a format string containing ordinary text and format specifiers that start with %. Each specifier consumes an argument and decides how it is printed: as a decimal integer, a fixed-point number, a padded string, a hexadecimal value and so on.
The engine behind them is Formatter. This page is the reference for the specifier syntax itself. Unlike C's printf, Java checks argument types at run time and throws an exception if they do not match.
System.out.printf("%-8s|%6.2f|%05d%n", "item", 3.14159, 42); // item | 3.14|00042
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
%[argument_index$][flags][width][.precision]conversion
Only % and the conversion character are required.
Conversions
| Conversion | Argument | Output |
|---|---|---|
d |
byte, short, int, long, BigInteger |
decimal integer |
x, X |
the same | hexadecimal (negative values use two's complement for primitives) |
o |
the same | octal |
f |
float, double, BigDecimal |
fixed-point, 6 decimals by default |
e, E |
the same | scientific notation, such as 1.234568e+04 |
g, G |
the same | scientific or fixed, depending on magnitude, precision counts significant digits |
a, A |
float, double |
hexadecimal floating point |
s, S |
any object | String.valueOf(arg), or formatTo() for a Formattable; S is upper case |
c, C |
char, Character, int code point |
a single character |
b, B |
any | false for null or false, otherwise true |
h, H |
any | hexadecimal of hashCode(), or null |
t, T |
date/time types | date or time part chosen by a suffix (%tF, %tY, %tH, ...) |
% |
none | a literal percent sign |
n |
none | the platform line separator |
Flags
| Flag | Meaning |
|---|---|
- |
left-justify within the width |
0 |
pad numbers with zeros |
+ |
always show a sign |
| space | leading space for positive numbers |
, |
locale grouping separators |
( |
negative numbers in parentheses |
# |
alternate form: 0x prefix for hex, always a decimal point for %f |
< (as an index) |
reuse the previous argument |
| Part | Description |
|---|---|
| width | minimum number of characters; shorter output is padded with spaces (or zeros with 0) |
| precision | for f, e: digits after the point; for g: significant digits; for s: maximum characters; not allowed for d, c |
n$ |
1-based index of the argument to use, instead of the next one |
Throws: UnknownFormatConversionException (bad conversion letter), MissingFormatArgumentException (too few arguments), IllegalFormatConversionException (type mismatch, e.g. %d with a double), IllegalFormatPrecisionException, IllegalFormatFlagsException, MissingFormatWidthException. All extend IllegalFormatException, which is unchecked.
Usage notes
- Rounding.
%fand%eround half-up, working from the short decimal text thatDouble.toString()would show. So%.1fof0.25gives0.3,%.0fof2.5gives3, and%.2fof1.005gives1.01even though the stored double is slightly below 1.005.DecimalFormatdefaults to half-even and uses the exact stored value, so it prints1.00for the same number. - Locale matters. The decimal separator, the grouping separator and the digits come from
Locale.getDefault(Locale.Category.FORMAT). A German default prints3,14. Pass a locale explicitly (printf(Locale.US, ...),String.format(Locale.ROOT, ...)) when you need predictable output such as file formats. %nover\n.%ngives the platform separator. Use\nwhen you need exactly one line feed character.- Extra arguments are ignored. Too many arguments is silent; too few throws.
%swithnullprintsnull. A%dwithnullalso printsnullrather than throwing.- Integers and
%f.%fdoes not accept anint; cast it or use%d.%ddoes not acceptdouble. %cwith an int treats it as a Unicode code point, so%cof66printsB.- Money. Use
BigDecimalwith%f/%,.2ffor currency instead ofdouble. - Performance. The format string is parsed on every call. In a hot loop, a
StringBuilderis faster; for human-facing messages the difference does not matter.