Loading lessons...
Printf Width and Precision
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:
printf("%5d", 25);
The number 25 is padded to 5 characters wide, mostly right-aligned:
25
Left-align with -
A minus sign flips the padding:
printf("%-5d|
", 25);
Prints 25 | with 25 on the left.
Precision for floats
.2f rounds to two decimals. Combine with a width:
printf("%8.2f\n", 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:
printf("%05d\n", 25); // 00025
TL;DR
%5dpads a number to width 5.%-5dleft-aligns it.%.2fsets decimal precision.%05dzero-pads the width.