C++ Format Output to 2 Decimal Places
To display two decimal places in C++, you can use the setprecision function from the iomanip header file. Here is a simple example:
#include <iostream>
#include <iomanip>
int main() {
double num = 3.14159;
std::cout << std::fixed << std::setprecision(2) << num << std::endl;
return 0;
}
In the above example, using std::fixed specifies the use of fixed-point decimal format, while std::setprecision(2) specifies retaining two decimal places. Running this code will output 3.14.