In C, use the `std::fixed` and `std::setprecision` functions (defined in the `
` header file) to preserve two decimal places in the output. `std::fixed` sets the output format to a fixed decimal point format, while `std::setprecision(2)` specifies keeping two decimal places.
In C, if you want to retain two decimal places when outputting, you can use std::setprecision and std::fixed functions, they are all defined in the
cpp
#include <iostream> #include <iomanip> int main() { double num = 3.141592653589793; std::cout << std::fixed << std::setprecision(2) << num << std::endl; return 0; }
In this example, std: :fixed sets the output format to a fixed decimal point format, and std::setprecision(2) sets the number of digits retained after the decimal point to 2. In this way, the output result is 3.14.
In addition, you also need to note that although std::setprecision sets the number of digits after the decimal point, it will not be rounded. If you need to round, you can use the std::round function, which is defined in the
cpp
#include <iostream> #include <iomanip> #include <cmath> int main() { double num = 3.141592653589793; num = std::round(num * 100.0) / 100.0; std::cout << std::fixed << std::setprecision(2) << num << std::endl; return 0; }
In this example, we first Multiply num by 100, then round, and finally divide by 100 to get the result to two decimal places. The output is still 3.14.
The above is the detailed content of How to retain two decimal places in c++ output. For more information, please follow other related articles on the PHP Chinese website!