Home >Backend Development >C++ >How to retain two decimal places in c++

How to retain two decimal places in c++

下次还敢
下次还敢Original
2024-04-26 18:36:11674browse

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.

How to retain two decimal places in c++

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn