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

How to retain two decimal places in c++ output

小老鼠
Release: 2024-03-25 16:07:25
Original
1774 people have browsed it

In C, use the `std::fixed` and `std::setprecision` functions (defined in the `` header file) to preserve two decimal places in the output. `std::fixed` sets the output format to a fixed decimal point format, while `std::setprecision(2)` specifies keeping two decimal places.

How to retain two decimal places in c++ output

In C, if you want to retain two decimal places when outputting, you can use std::setprecision and std::fixed functions, they are all defined in the header file. Here is an example:

cpp

#include <iostream>  
#include <iomanip>  
  
int main() {  
    double num = 3.141592653589793;  
    std::cout << std::fixed << std::setprecision(2) << num << std::endl;  
    return 0;  
}
Copy after login

In this example, std: :fixed sets the output format to a fixed decimal point format, and std::setprecision(2) sets the number of digits retained after the decimal point to 2. In this way, the output result is 3.14.

In addition, you also need to note that although std::setprecision sets the number of digits after the decimal point, it will not be rounded. If you need to round, you can use the std::round function, which is defined in the header file. Here is an example:

cpp

#include <iostream>  
#include <iomanip>  
#include <cmath>  
  
int main() {  
    double num = 3.141592653589793;  
    num = std::round(num * 100.0) / 100.0;  
    std::cout << std::fixed << std::setprecision(2) << num << std::endl;  
    return 0;  
}
Copy after login

In this example, we first Multiply num by 100, then round, and finally divide by 100 to get the result to two decimal places. The output is still 3.14.

The above is the detailed content of How to retain two decimal places in c++ output. 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