Lesson 35 +10 XP

Decimal Precision

Decimal Precision

When you print a float or double, C wants to know how many decimals to show. That's called precision.

The default is noisy

float myFloat = 5.99;
printf("%f", myFloat);

Output: 5.990000 - printf adds six decimals by default.

Setting precision

A . plus a number between the % and the specifier sets the decimals:

printf("%.1f", 5.99);    // 6.0
printf("%.2f", 5.99);    // 5.99
printf("%.4f", 5.99);    // 5.9900

Rounding

printf rounds, not truncates: %.1f of 5.99 gives 6.0.

Combined with width

printf("%8.2f", 3.14);   // "    3.14"

TL;DR

  • %f prints six decimals by default.
  • %.Nf prints N decimals.
  • printf rounds to the requested precision.
  • Combine with width: %8.2f.