Skip to main content

Print float to 2 and 4 decimals

Short answer

Use printf("%.2f", x) for two decimal places and printf("%.4f", x) for four decimal places, which rounds the value. For x = 3.14159, output becomes 3.14 and 3.1416 respectively.

Write a program that prints the floating point value with following specification. i) Correct up to two decimal places ii) Correct up to four decimal places.

The precision in the %f specifier (%.nf) sets the number of digits after the decimal point; the value is rounded.

#include <stdio.h>
int main(void)
{
    float x = 3.14159265f;
    printf("Two decimal places : %.2f\n", x);
    printf("Four decimal places: %.4f\n", x);
    return 0;
}

Output:

Two decimal places : 3.14
Four decimal places: 3.1416

✓ Answer checked by Claude Opus 5.5 (high effort)

All Computer Programming chapter 4 questions →