Home > Backend Development > C++ > How to retain 2 decimal places for output in c++

How to retain 2 decimal places for output in c++

下次还敢
Release: 2024-04-26 15:36:13
Original
1360 people have browsed it

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 2 decimal places for output in c++

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.

<code class="cpp">#include <iostream>
#include <iomanip>

using namespace std;

int main() {
  double value = 123.456789;

  // 设置保留两位小数
  cout << fixed << setprecision(2) << value << endl;

  return 0;
}</code>
Copy after login

Output:

<code>123.46</code>
Copy after login

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 
#include 

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template