There are two ways to retain two decimal places in output in C: 1. Use std::fixed and std::setprecision to control the output stream formatting, such as: cout << fixed << setprecision (2) << value; 2. Use std::to_string and std::substr to convert the number to a string and extract the number of decimal places, such as: string result = str.substr(0, str.find('. ') 3);
How to retain two decimal places in C output?
There are two ways to retain two decimal places in output in C:
1. Use std::fixed and std::setprecision
This method is implemented by controlling the formatting of the output stream.
#include <iostream> #include <iomanip> using namespace std; int main() { double value = 123.456789; // 设置保留两位小数 cout << fixed << setprecision(2) << value << endl; return 0; }
Output:
<code>123.46</code>
2. Using std::to_string and std::substr
This method involves converting a number to a string, Then extract the required number of decimal places.
#include <iostream> #include <string> using namespace std; int main() { double value = 123.456789; // 转换为字符串 string str = to_string(value); // 提取两位小数 string result = str.substr(0, str.find('.') + 3); cout << result << endl; return 0; }
Output:
<code>123.46</code>
The above is the detailed content of How to retain 2 decimal places for output in c++. For more information, please follow other related articles on the PHP Chinese website!