Here we will see how to print some floating point numbers up to some pre-defined decimal places. In C++, we can use setprecision with the cout to do this word. This is present under the iomanip header file in C++.
Example Code
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
double x = 2.3654789d;
cout << "Print up to 3 decimal places: " << setprecision(3) << x << endl;
cout << "Print up to 2 decimal places: " << setprecision(2) << x << endl;
cout << "Print up to 7 decimal places: " << setprecision(7) << x << endl;
}Output
Print up to 3 decimal places: 2.365 Print up to 2 decimal places: 2.37 Print up to 7 decimal places: 2.3654789