← Back

14. Width and Precision Combined

Medium

📝 Problem

Accept a floating point value and print it with 20 width space and round off to 4 decimal places.

Input Format:
Accept a floating point value
Output Format:
Print the give value with width 20 and rounded off to 4 decimal places
Constraints:
2.3E-308 to 1.7E+308
💡 Combining Width and Precision

This problem combines two important formatting concepts:

  • setw(20) - Sets the output width to 20 characters (right-aligned by default)
  • setprecision(4) - With fixed, shows exactly 4 decimal places
  • fixed - Prevents scientific notation and enables decimal precision

📚 Want to learn more about setw()?

📖 Read Question #9: Complete Guide to setw, setfill & Alignment →

How it works together:

Visual Example (width = 20):
|----5----|----10---|----15---|----20|
Input: 12.45678
Output: 12.4568
↑ 12 spaces + 7 chars (12.4568) = 20 total width

Order matters!

  • fixedsetprecision(4)setw(20)
  • The number is first formatted with precision, then padded to width

Key Differences:

  • setw() - Affects total width (including decimal point and digits)
  • setprecision() - Only affects digits after decimal point
  • setw() is temporary - applies only to next output
  • fixed and setprecision() are persistent

Examples

Sample Input 1:
Input:
12.45678
Sample Output 1:
Output:
12.4568
Note: 12 leading spaces + "12.4568" (7 chars) = 20 total width
Sample Input 2:
Input:
19.45789
Sample Output 2:
Output:
19.4579
Note: Rounded from 19.45789 to 19.4579 (4 decimal places)
Solution.cpp
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    long double f;
    cin >> f;
    
    // fixed: Prevents scientific notation
    // setprecision(4): Exactly 4 decimal places
    // setw(20): Total width of 20 characters
    cout << fixed << setprecision(4) << setw(20) << f;
    
    return 0;
}