Advertisement
Advertisement


Printing the correct number of decimal points with cout


Question

I have a list of float values and I want to print them with cout with 2 decimal places.

For example:

10.900  should be printed as 10.90
1.000 should be printed as 1.00
122.345 should be printed as 122.34

How can I do this?

( setprecision doesn't seem to help in this.)

2015/04/22
1
133
4/22/2015 5:44:57 AM

Accepted Answer

With <iomanip>, you can use std::fixed and std::setprecision

Here is an example

#include <iostream>
#include <iomanip>

int main()
{
    double d = 122.345;

    std::cout << std::fixed;
    std::cout << std::setprecision(2);
    std::cout << d;
}

And you will get output

122.34
2016/01/19
197
1/19/2016 6:14:45 PM

You were nearly there, need to use std::fixed as well, refer http://www.cplusplus.com/reference/iostream/manipulators/fixed/

#include <iostream>
#include <iomanip>

int main(int argc, char** argv)
{
    float testme[] = { 0.12345, 1.2345, 12.345, 123.45, 1234.5, 12345 };

    std::cout << std::setprecision(2) << std::fixed;

    for(int i = 0; i < 6; ++i)
    {
        std::cout << testme[i] << std::endl;
    }

    return 0;
}

outputs:

0.12
1.23
12.35
123.45
1234.50
12345.00
2011/05/06

setprecision(n) applies to the entire number, not the fractional part. You need to use the fixed-point format to make it apply to the fractional part: setiosflags(ios::fixed)

2011/05/06

Simplify the accepted answer

Simplified example:

#include <iostream>
#include <iomanip>

int main()
{
    double d = 122.345;
    std::cout << std::fixed << std::setprecision(2) << d;
}

And you will get output

122.34

Reference:

2015/06/02

I had an issue for integers while wanting consistent formatting.

A rewrite for completeness:

#include <iostream>
#include <iomanip>

int main()
{
    //    floating point formatting example

    double d = 122.345;
    cout << std::fixed << std::setprecision(2) << d << endl;
    //    Output:  122.34


    //    integer formatting example

    int i = 122;
    cout << std::fixed << std::setprecision(2) << double(i) << endl;
    //    Output:  122.00
}

I had this similar problem in a coding competition and this is how I handled it. Setting a precision of 2 to all double values

First adding the header to use setprecision

#include <iomanip>

Then adding the following code in our main

  double answer=5.9999;
  double answer2=5.0000;
  cout<<setprecision(2)<<fixed;
  cout <<answer << endl;
  cout <<answer2 << endl;

Output:

5.99
5.00

You need to use fixed for writing 5.00 thats why,your output won't come for 5.00.

A short reference video link I'm adding which is helpful

2017/07/25

Source: https://stackoverflow.com/questions/5907031
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]