Round off the given floating point value with accurate to 2 decimal places.
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)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!
#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;
}