- 2069 Chaitra · 2 marks
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)
Related questions
- Correct program: do-while and pow · Computer Programming, chapter 3
- Correct program: Celsius to Fahrenheit · Computer Programming, chapter 3
- Correct program: case array and average · Computer Programming, chapter 3
- Correct program: character arrays · Computer Programming, chapter 7
- Decimal to binary conversion · Computer Programming, chapter 5
- Binary to decimal in FORTRAN · Computer Programming, chapter 11
- Exception with argument and specification program · Object Oriented Programming, chapter 10
- Floating point addition and subtraction · Computer Organization and Architecture, chapter 5 · asked 6×
- Floating point division algorithm · Computer Organization and Architecture, chapter 5 · asked 4×
- Floating point multiplication · Computer Organization and Architecture, chapter 5 · asked 3×