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

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

下次还敢
下次还敢Original
2024-04-26 15:36:131278browse

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>

Output:

<code>123.46</code>

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>

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!

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