How to output a number in C++ with two decimal places?

In C++, you can use the setprecision function from the iomanip header file to set the precision of decimal output. Here is an example code:

#include <iostream>
#include <iomanip>

int main() {
    double number = 3.1415926;
    
    std::cout << std::fixed << std::setprecision(2) << number << std::endl;
    
    return 0;
}

In the above code, setprecision(2) is used to set the precision of the output decimal to two digits. By using fixed to lock the position of the decimal point, it ensures that the output is a decimal rather than in scientific notation.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds