Loading lessons...
Printf Width and Precision
printf can pad numbers, rotate decimals, and line up columns. These options go right after the %.
Width with %d
A number after % sets the minimum width:
c
printf("%5d", 25);
The number 25 is padded to 5 characters wide, mostly right-aligned:
text
25
Left-align with
- A minus sign flips the padding:
c
printf("%-5d|
", 25);
Prints 25 | with 25 on the left.
Precision for floats
.2f rounds to two decimals. Combine with a width:
c
printf("%8.2f
", 3.14159); // " 3.14"
The result is painted to 8 wide total, 2 decimals.
Zero padding
A leading 0 pads with zeros instead of spaces:
c
printf("%05d
", 25); // 00025
TL;DR
%5dpads a number to width 5.%-5dleft-aligns it.%.2fsets decimal precision.%05dzero-pads the width.