You can control how floating point numbers are displayed using various formatting options in C++. Here are some common approaches:
precision()
The simplest way is to set how many decimal places to show using precision()
:
#include <iostream>
using namespace std;
int main() {
float Pi{3.14159265359};
// Default output
cout << "Default Pi: " << Pi << '\n';
// Set to 2 decimal places
cout.precision(2);
cout << "Pi with 2 digits: " << Pi << '\n';
// Set to 4 decimal places
cout.precision(4);
cout << "Pi with 4 digits: " << Pi;
}
Default Pi: 3.14159
Pi with 2 digits: 3.1
Pi with 4 digits: 3.142
fixed
Sometimes we want to always show a specific number of decimal places, even if they're zeros. We can use fixed
for this:
#include <iostream>
using namespace std;
int main() {
float Price{19.99};
float WholeNumber{20.0};
// Set to show exactly 2 decimal places
cout.precision(2);
cout << fixed;
cout << "Price: $" << Price;
cout << "\nWhole number: $" << WholeNumber;
// You can turn off fixed mode if needed
cout.unsetf(ios::fixed);
cout << "\nBack to default: " << Price;
}
Price: $19.99
Whole number: $20.00
Back to default: 20
showpoint
If you want to always show the decimal point, even for whole numbers, use showpoint
:
#include <iostream>
using namespace std;
int main() {
float Score{100.0};
// Default - no decimal for whole numbers
cout << "Score: " << Score << '\n';
// Force showing decimal point
cout << showpoint;
cout << "Score with decimal: " << Score;
}
Score: 100
Score with decimal: 100.000
Remember:
Answers to questions are automatically generated and may not have been reviewed.
Explore how C++ programs store and manage numbers in computer memory, including integer and floating-point types, memory allocation, and overflow handling.