简体   繁体   中英

How to output an interger which is calculated to two decimal places?

It is easy to output a double value which is calculated to two decimal places. And the code snippet is below:

cout.setf(ios_base::showpoint);
cout.setf(ios_base::fixed, ios_base::floatfield);
cout.precision(2);
cout << 10000000.2 << endl;       // output: 10000000.20
cout << 2.561452 << endl;         // output: 2.56
cout << 24 << endl;               // output: 24         but I want 24.00, how to change my code?

How to output an interger which is calculated to two decimal places? I want 24.00 as an output.

It depends on what your 24 is.

If it is a hard-coded value, you can just write:

std::cout << 24.00 << std::endl;

If it's an integer variable, write this:

std::cout << static_cast<double>(myIntegerVariable) << std::endl;

Don't use any of the suggested approaches like adding ".00" as this will break your code if you want to change the precision later.

A rewrite of completeness, please try with following

#include <iostream>
#include <iomanip>

int main()
{
    int i = 24;
    std::cout << std::fixed << std::setprecision(2) << double(i) << std::endl;
    //    Output:  24.00
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM