I want to print a floating-point number with 2 decimal places. For example, 3.444 should output as 3.44 and 99999.4234 as 99999.42. My code is:
#include <iomanip>
#include <iostream>
using namespace std;
int main() {
double num1 = 3.12345678;
cout << fixed << showpoint;
cout << setprecision(2);
cout << num1 << endl;
}
But I get an error saying undefined fixed symbol. How can I correctly use setprecision C++ to format my numbers?
Without fixed, setprecision affects total significant digits, not decimals:
double num = 3.444;
std::cout << std::setprecision(2) << num << std::endl; // Output: 3.4
With fixed, it controls digits after the decimal:
std::cout << std::fixed << std::setprecision(2) << num << std::endl; // Output: 3.44
I always combine fixed + setprecision when I want exact decimal formatting.
I personally like being explicit instead of using namespace std;:
#include <iostream>
#include <iomanip>
int main() {
double num1 = 99999.4234;
std::cout << std::fixed << std::showpoint << std::setprecision(2);
std::cout << num1 << std::endl; // Output: 99999.42
}
Works exactly the same and avoids namespace pollution.
I use this style in professional codebases.
I’ve seen this error before
. The problem usually happens if fixed or setprecision isn’t recognized. Make sure you:
Include <iomanip>
Use std:: or using namespace std;
Correct code:
#include <iostream>
#include <iomanip> // needed for fixed and setprecision
using namespace std;
int main() {
double num1 = 3.12345678;
cout << fixed << showpoint << setprecision(2);
cout << num1 << endl; // Output: 3.12
return 0;
}
fixed ensures decimal precision, not significant digits.
setprecision(2) formats the number to 2 digits after the decimal.