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

下次还敢
Release: 2024-04-26 18:33:14
Original
848 people have browsed it

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 thestd::fixedandstd::setprecision()functions.

1. std::fixed

std::fixedRepresents a floating point number as a fixed number of decimal places. By default, floating point numbers are represented in scientific notation, whilestd::fixedconverts 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:

#include  #include  using namespace std; int main() { double value = 123.4567; // 保留 2 位小数输出而不四舍五入 cout << fixed << setprecision(2) << value << endl; return 0; }
Copy after login

Output:

123.45
Copy after login

In this example,std::fixedConvertsvalueto decimal notation whilestd::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!

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 Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!