The way to preserve two decimal places in C is to specify fixed-point notation using the stream operator fixed. Use setprecision(2) to specify 2 decimal places.
Retaining two decimal places in C
The way to retain two decimal places in C is to use stream operations Symbolsfixed
andsetprecision
.fixed
specifies the use of fixed point notation,setprecision
specifies the number of digits after the decimal point.
To preserve two decimal places, use the following code:
cout << fixed << setprecision(2) << myNumber;
wheremyNumber
is the floating point number you want to preserve decimal places.
Example:
#include using namespace std; int main() { double myNumber = 123.4567; cout << "原来的数字:" << myNumber << endl; cout << "保留两位小数:" << fixed << setprecision(2) << myNumber << endl; return 0; }
Output:
原来的数字:123.4567 保留两位小数:123.46
The above is the detailed content of How to retain two decimal places in c++. For more information, please follow other related articles on the PHP Chinese website!