News Ticker

How to Format a String, Clarified!

Java String Format

A User-Friendly Introduction

The Java Documentation of String formatting is not the easiest to read and understand if you are not familiar with String formatting or just want a quick solution. Although it is complete, it is not very user-friendly, so I thought I would try and write a clearer version. This article is as much for you as it is an aide memoir for myself.

The Format Methods

There are two methods that provide String formatting behavior: format() and printf(). The format() method is a static method of the String.class and the printf() method is a method of the static System.out.class. They both behave exactly the same way and have the same signature.

format("format string", argument(s));
printf("format string", argument(s));

The “format string” is used to format the values in the argument list.

It can contain both String literals information that isn’t associated with any arguments and argument-specific formatting data. Formatting data will always start with a percent sign (%) followed by the formatting semantics.

Let’s look at some examples.

Replace a Placeholder in a String

Let’s start with the simplest example. In the code snippet below the placeholder, %s is replaced by the name Alex.

String.format("Hello %s", "Alex");
// Hello Alex

The format() method returns a String containing the message Hello Alex.

Mulitple Placeholders

More than one placeholder can be replaced at a time. In the following example, the formatted String consists of a String and a floating point primitive.

String.format("The %s costs $%f", "Bag", 12.99f);
// The Bag costs $12.990000

Notice how the number is not formatted as a currency two-decimal number. Let’s look at number formatting next.

How to Format a Number

To format a number to a given number of decimal places specify the number of places after the % placeholder character as shown in the following code snippet.

String.format("The %s costs $%.2f", "Bag", 12.99f);
// The Bag costs $12.99

Add Number Separator

To add a number separator include the comma character after the % placeholder.

String.format("The %s costs $%,.2f", "Car", 54999.99f);
// The Car costs $54,999.99

The comma is locale-specific so the dot (.) separator would be used in regions that use that character to group numbers.

Let’s have quick look at other number formatting options.

Enclose negative number in parenthesis

Use the ( character to indicate that negative numbers should be enclosed in parenthesis.

String.format("Absolute zero is %(.2f degrees Celsius", -273.15f);
// Absolute zero is (273.15) degrees Celsius

Include positive or negative sign

Use the + character to include a positive or negative sign.

String.format("Temperature of the Sun %,+d K", 5778);
// Temperature of the Sun +5,778 K
String.format("Temperature of Jupiter %,+d Celsius", -145);
// Temperature of Jupiter -145 Celsius

Padding a number with zeros

Padding a number with zeros is done with the 0 flag and by specifying the width. In the code below the width is 10.

String.format("A padded number %010d", 42);
// A padded number 0000000042

Note that the number of zeros in not 10, but the width of the number is 10 with the remaining space after the number filled with zeros to make the number 10 digit long.

Left Justify a Number

The number can be displayed justify to the left and with a given width.

String.format("A left-justified number <%-10d>", 42);
// A left-justified number <42        >

Note that the number of spaces to the left in not 10, but the width of the number is 10 with the remaining space after the number filled with the space character to make the number characters long.

Octal and Hexadecimal numbers

There are two formatting options for displaying Octal and Hexadecimal numbers: with a leading 0 or 0x or without any leading characters.

String.format("An octal number %o", 100);
// An octal number 144
String.format("An octal number %#o", 100);
// An octal number 0144
String.format("An hex number %x", 100);
// An hex number 64
String.format("An hex number %#X", 100);
// An hex number 0X64

Note the capital X in the last example. The case of the X determines the case of the X in the output number i.e. a lowercase x results in a lowercase X in the output number.

Number Flag Round-Up

To round-up what I have talked about so far I have prepared a table summarising the flags. This is not an exhaustive list, for you must consult the Java documentation.

Flag Description Notes
Left justify this argument. Cannot use with Pad “0”. Must also specify a width.
+ Include a sign (+ or – ) with this argument Only with numbers. d or f.
0 Pad this argument with zeroes. Only with numbers. Must also specify a width. d or f.
,
Use locale-specific grouping separators (i.e., the comma in 123,456)
Only with numbers. d or f.
(
Enclose negative numbers in parentheses
Only with numbers. d or f.

The format specifier for general, character, and numeric types have the following syntax:

The format string: %[arg_index$][flags][width][.precision]conversion character

The values within square brackets [ ] are optional, the only required elements of a format string are the percentage character % and a conversion character.

Conversion Characters

To round-up the conversion characters I have talked about I have constructed a summary table. This is not an exhaustive list, for you must consult the Java documentation.

Conversion character Type Notes
d integral Decimal integer
o integral Octal integer
x, X integral Hexadecimal integer
e, E floating point Decimal number in scientific notation
f floating point Decimal number
t, T date/time Prefix for date and time conversion characters
% percent Literal %

How to Format a String

Strings can be formatted in very much the same way as for numbers and will use many of the same flags. Let’s start by looking at a String formatted with several arguments.

Multiple Arguments

The formatted string can contain multiple arguments of different types. The following example has two arguments: one is a String and the other is an integer.

String.format("The %1s has %2d moons", "Saturn", 53);
// The Saturn has 53 moons

Notice the format of the argument. The number refers to the order of the parameters following the String. For example, %1s refers to the 1st argument and %2d refers to the second argument.

Formatting a String

A string can be subject to the same formatting as numbers. Let’s see some quick examples:

Specify a Width

String.format("Fun with <%10s>", "Java");
// Fun with <      Java>

Specify a Left Justification with Width

output = String.format("Fun with <%-10s>", "Java");
// Fun with <Java      >

Truncate the Maximum Number of Characters

output = String.format("Fun with <%.1s>", "Java");
// Fun with <J>

Final Words

Here are a few compound examples that combine flags, width, precision, and a conversion character.

System. out.printf( "%2$(+,8d, %1$(+,8d", 1234, -5678);
// (5.678),   +1.234
  • ( show braces around negative numbers
  • + show + for positive numbers
  • , use local number formats
  • 8 minimum width of 8
  • d digits
System. out.printf( "%2$0+,8d, %1$0+,8d", 1234, -5678);
// -005.678, +001.234
  • 0 fill spaces with 0’s
 
System. out.printf( "%2$-+,8d, %1$-+,8d", 1234 ,-5678);
// -5.678, +1.234
  •   justify left
System. out.printf( "%1$+,8.4f", 12234.678878);
// +12.234,6789
  • + show + for positive numbers
  •  , use local number formats
  • 8 minimum width of 8
  • .4 the number of digits after the point, rounded
  • f floats

Conclusion

String formatting is a complex topic and to be sure you know all the details please refer to Java Documentation.

Code Source

The code source for this article is in my GitHub repository.

Further Reading

I usually publish posts about Java EE. Here is a short list of topics that might interest you:

Learn More

If you want to level-up you Java EE skills try my Lynda.com video training courses. They cover a selection of Java EE technologies:

 

 

1 Trackback / Pingback

  1. Java Annotated Monthly – October 2017 | IntelliJ IDEA Blog

Leave a Reply

%d bloggers like this: