

To zero-fill your printf integer output, just add a zero ( 0) after the % symbol, like this: printf("%03d", 0) Īs a summary of printf integer formatting, here’s a little collection of integer formatting examples. To left-justify integer output with printf, just add a minus sign ( -) after the % symbol, like this: printf("%-3d", 0) The %3d specifier is used with integers, and means a minimum width of three spaces, which, by default, will be right-justified: printf("%3d", 0) Here’s a quick summary of the available printf format specifiers: %c In the remainder of this document I’ll use Perl examples, but again, the actual format specifier strings can be used in many different languages.

String result = String.format("the %s jumped over the %s, %d times", "cow", "moon", 2) Īs you can see in that last String.format example, that line of code doesn’t print any output, while the first line prints to standard output, and the second line prints to standard error. ("the %s jumped over the %s, %d times", "cow", "moon", 2)

Printf("the %s jumped over the %s, %d times", "cow", "moon", 2) Īnd here are three different Java printf examples, using different string formatting methods that are available to you in the Java programming language: Therefore, here’s a simple Perl printf example to get things started: In this cheat sheet I’ll show all the examples using Perl, but at first it might help to see one example using both Perl and Java. This means that your printf knowledge is reusable, which is a good thing. I originally created this cheat sheet for my own programming purposes, and then thought I would share it here.Ī great thing about the printf formatting syntax is that the format specifiers you can use are very similar - if not identical - between different languages, including C, C++, Java, Perl, PHP, Ruby, Scala, and others. Summary: This page is a printf formatting cheat sheet or reference page.
