Home >Backend Development >C++ >How to keep 2 decimal places in output without rounding in c++

How to keep 2 decimal places in output without rounding in c++

下次还敢
下次还敢Original
2024-04-26 18:33:141024browse

In C, to preserve two decimal places in the output without rounding, you can use the following steps: Use std::fixed to represent floating point numbers with a fixed number of decimal places. Use std::setprecision() to set the number of decimal places to retain, including the decimal point.

How to keep 2 decimal places in output without rounding in c++

How to retain 2 decimal places in C output without rounding

In C, 2 decimal places must be retained To output without rounding, use the std::fixed and std::setprecision() functions.

1. std::fixed

std::fixed Represents a floating point number as a fixed number of decimal places. By default, floating point numbers are represented in scientific notation, while std::fixed converts them to decimal notation, preserving the specified number of digits.

2. std::setprecision()

std::setprecision() Set the number of decimal places to be retained. For floating point numbers, std::setprecision() Specifies the number of decimal places to display, including the decimal point.

Sample code:

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

using namespace std;

int main() {
  double value = 123.4567;

  // 保留 2 位小数输出而不四舍五入
  cout << fixed << setprecision(2) << value << endl;

  return 0;
}</code>

Output:

<code>123.45</code>

In this example, std::fixed Converts value to decimal notation while std::setprecision(2) specifies that 2 decimal places be preserved. Therefore, the output is rounded to 2 decimal places without rounding.

The above is the detailed content of How to keep 2 decimal places in output without rounding 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
Previous article:What does /* mean in c++Next article:What does /* mean in c++