Last Updated:

Format and output numbers in java

Most beginners who have seen documentation on string formatting in Java in the official help find it difficult. We will try to give a more understandable guide on this topic.

The most popular formatting method is String.format().

Stringoutput = String.format(«%s = %d», «joe», 35)
System.out.printf(«Mynameis: %s%n», «joe»);

For formatted output to the console, use: System.errPrintStreams and printf() or the format() method System.out.

System.out and System.err (standard output and error output streams, respectively) are of type PrintStream. This means that you will learn how to use the System.out.format(), System.err method. the format() and String.format() methods. In this case, the syntax of this method is the same for all classes: the format (strings, object... arguments).

String includes aggregate text embedded with format specifiers. They must follow the following syntax: %[argument_index$][flags][width][.precision]conversion. In this case, the elements inside the brackets are optional. Let's take a closer look at each of the elements:

  • % - indicates the beginning of the format specification.
  • arguments_index (optional argument) is a decimal integer that indicates the position of an argument in the argument list. That is, the first argument refers to "$ 1", and the second, respectively, "$ 2" and so on.
  • flags is a set of characters that change the output format.
  • width is a positive decimal integer that specifies the minimum number of characters written to the output.
  • precision is a non-negative decimal integer that is most commonly used to limit the number of characters.
  • conversion—A special character that indicates how the argument should be formatted.
string format method in java

The printf() method does exactly the same as the format() method. The format method (Stringformat, Object... args) formats the string by default. The format method (localelocale, Stringformat, Object... args) formats the string according to the specified standard.

Create a formatter, and then associate it with a StringBuilder. The output formatted with the format() method is appended to the StringBuilder.

StringBuildersbuf = newStringBuilder();
Formatterfmt = newFormatter(sbuf);
fmt.format(«PI = %f%n», Math.PI);
System.out.print(sbuf.toString());

Java Format Specifiers

 

Here's a quick reference to all the specifiers supported by Java.

TypeSpecifierInference
floatingpoint (exceptBigDecimal)%aHexadecimal floating-point number output
Anytype%b"true" if not 0, "false" if 0
character%cUnicode
integer (incl. byte, short, int, long, bigint)%dDecimal integer
floatingpoint%edecimal number in a scientific record
floatingpoint%fdecimal
floatingpoint%gdecimal number, possibly in scientific notation depending on accuracy and meaning.
anytype%hThe hexadecimal string of the value from the hashCode() method.
none%nA platform-specific string separator.
integer (incl. byte, short, int, long, bigint)%oOctal number
anytype%sString value
Date/Time (incl. long, Calendar, DateandTemporalAccessor)%t%t is the prefix for the date/time conversion.
integer (incl. byte, short, int, long, bigint)%xA hexadecimal string.
 

Format integers

You can use the %d format specifier to apply arguments of all integer types, including short, int, byte, long, and BigInteger.

Default formatting:

String.format(«%d», 93); // prints 93

Specifying the width:

String.format(«|%20d|», 93); // prints: | 93|

Left alignment within the boundaries of the specified width:

String.format(«|%-20d|», 93); // prints: |93 |

Display positive numbers with a "+" sign:

(Negative numbers contain «-»):
String.format(«|%+20d|’, 93); // prints: | +93|

The gap before the positive numbers.

String.format(«|% d|», 93); // prints: | 93| String.format(«|% d|», -36); // prints: |-36|

Place the negative numbers in parentheses ("()") and skip the "-":

String.format(«|%(d|», -36); // prints: |( 36)|

Octal conclusion:

String.format(«|%o|»), 93); // prints: 135

Hexadecimal output:

String.format(«|%x|», 93); // prints: 5d

Alternatives for octal and hexadecimal output:

Prints octal numbers with an initial "0" and hexadecimal numbers with an initial "0x".
String.format(«|%#o|», 93);
// prints: 0135
String.format(«|%#x|», 93);
// prints: 0x5d
String.format(«|%#X|», 93);
// prints: 0X5D

Format strings and characters

Default formatting:

Prints the entire line.

String.format(«|%s|», «HelloWorld»); // prints: «HelloWorld»

With an indication of the length of the field:

String.format(«|%30s|», «HelloWorld»); // prints: | HelloWorld|

Left alignment:

String.format(«|%-30s|», «HelloWorld»); // prints: | HelloWorld |

Displays the maximum number of characters:

String.format(«|%.5s|», «HelloWorld»); // prints: | Hello|

Specifies the width of the field and the maximum number of characters:

String.format(«|%30.5s|», «HelloWorld»); | Hello|

Examples

Sample code that formats a string, an integer, and a floating-point number. Precision to two numbers after the decimal point (.2f):

Stringtitle = «EffectiveJava»;
floatprice = 33.953f;
System.out.format(«%s is a greatbook. Itissoldat %.2f USD today.%n», title, price);

Inference:

EffectiveJavais a greatbook. Itissoldat 33.95 USD today.

An example of using the '-' flag to align lines with a width of 30 characters to the left:

List<string>listBook = Arrays.asList(
«HeadFirstJava»,
«EffectiveJava»,
«ThePassionateProgrammer»,
«HeadFirstDesignPatterns»
);
for(Stringbook :listBook){
System.out.format(«%-30s — InStock%n», book);
} </string>

An example of printing numbers in both decimal (%d) and hexadecimal format (%x and %#x):

System.out.format(«Minvalueof a byte: %d (%1$#x)%n», Byte.MIN_VALUE);
System.out.format(«Maxvalueof a byte: %d (%1$#x)%n», Byte.MAX_VALUE);
System.out.format(«Minvalueofanint: %d (%1$x)%n», Integer.MIN_VALUE);
System.out.format(«Maxvalueofanint: %d (%1$x)%n», Integer.MAX_VALUE);

Attention! There are two format specifiers, but only one argument, so we use the index of the argument 1$ to indicate the position of the argument for the specifier.

Result:

Minvalueof and Apartment: -128 (0x80)
Maxvalueof and Apartment: 127 (0x7f)
Minvalueofanint: -2147483648 (80000000)
Maxvalueofanint: 2147483647 (7fffffff)

The following code uses the t prefix with date and time conversions (T, F, and D) to write the formatted current time and date strings to a file:

PrintWriterwriter = newPrintWriter(newFile(«datetime.txt»));
writer.format(«Nowis %tT %n», newDate());
writer.format(«Todayis %tF %n», newDate());
writer.format(«Todayis %tD %n», newDate());
writer.close();

The output is a file (datetime.txt) with the following content:

Nowis 23:25:11
Todayis 2016-12-14
Todayis 12/14/16

The following code formats a Date object into a string using the full local name of the day of the week (tA), the name of the month (tB), the day of the month (td), and the four-digit year (tY):

code in java

String.format() returns a formatted string, specify the < to show that this specifier uses the same argument as the previous one. Conclusion: TodayisWednesdayDecember 14, 2016

Next, format the output so that it looks like columns:

Stringspecifiers = «%-30s %-20s %-5.2f%n»;
System.out.format(specifiers, «HeadFirstJava», «KathySierra», 23.99f);
System.out.format(specifiers, «ThinkinginJava», «BruceEckel», 25.69f);
System.out.format(specifiers, «EffectiveJava», «JoshuaBloch», 27.88f);
System.out.format(specifiers, «ThePassionateProgrammer», «ChadFowler», 41.99f);
System.out.format(specifiers, «CodeComplete», «SteveMcConnell», 38.42f);

Now the most difficult thing is to format numbers in Java with the addition of zero for numbers less than 5 characters (%05d); bracket the negative numbers (%(d) and include a character for the numbers (% + d):

System.out.format(«%05d %n», 12);
System.out.format(«%05d %n», 2016);
System.out.format(«%05d %n», 365);
System.out.format(«%05d %n», 19001800);
System.out.format(«%(d %n», -1234);
System.out.format(«%+d %n», 567);
System.out.format(«%+d %n», -891);

Get:

00012
02016
00365
19001800
(1234)
+567
-891