Lesson 20 +10 XP

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

  • %5d pads a number to width 5.
  • %-5d left-aligns it.
  • %.2f sets decimal precision.
  • %05d zero-pads the width.