Home > Backend Development > C++ > body text

How to retain two decimal places in c++

下次还敢
Release: 2024-04-26 18:36:11
Original
627 people have browsed it

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>
Copy after login

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>
Copy after login

Output:

<code>原来的数字:123.4567
保留两位小数:123.46</code>
Copy after login

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!

Related labels:
c++
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template