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 Symbols fixed
and setprecision
. 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:
<code class="cpp">cout << fixed << setprecision(2) << myNumber;</code>
where myNumber
is the floating point number you want to preserve decimal places.
Example:
<code class="cpp">#include <iostream> using namespace std; int main() { double myNumber = 123.4567; cout << "原来的数字:" << myNumber << endl; cout << "保留两位小数:" << fixed << setprecision(2) << myNumber << endl; return 0; }</code>
Output:
<code>原来的数字:123.4567 保留两位小数:123.46</code>
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!