← Back

13. Format Float with Precision

Medium

📝 Problem

Round off the given floating point value with accurate to 2 decimal places.

Input Format:
Accept a floating point value
Output Format:
Print the value accurate to 2 decimal places
Constraints:
3.4E-4932 <= inp <= 1.1E+4932
💡 Understanding Floating-Point Formatting

Why use fixed and setprecision?

By default, C++ displays floating-point numbers in a way that might surprise you. For precise control over decimal places, you need the <iomanip> library.

  • fixed - Forces fixed-point notation (not scientific like 1.23e+5)
  • setprecision(n) - Sets exactly n digits after the decimal point when used with fixed

Without vs With Formatting:

Input Without fixed With fixed
12.53412 12.53 12.53
12.5 12.5 12.50
1000.0 1e+03 1000.00

Key Points:

  • fixed prevents scientific notation (e.g., 1.23e+5)
  • ✅ Automatically rounds to the specified decimal places
  • ✅ Pads with zeros if needed (12.5 → 12.50)
  • ✅ Works with float, double, and long double

Important: Once you use fixed and setprecision, they remain active for all subsequent outputs in that program unless you change them!

Examples

Sample Input 1:
Input:
12.53412
Sample Output 1:
Output:
12.53
Sample Input 2:
Input:
-165.12859
Sample Output 2:
Output:
-165.13
Solution.cpp
#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    long double f;
    cin >> f;
    
    // fixed: Use fixed-point notation (not scientific)
    // setprecision(2): Show exactly 2 decimal places
    cout << fixed << setprecision(2) << f;
    
    return 0;
}