0

How would I modify code, like the code shown below, to exclude the constant VALUE_1 when using setprecision(2) so that it will display 3 decimals instead of 2 like the others?

#include <iostream>
#include <iomanip>

using namespace std;

const double VALUE_1 = .011;

int main(void)
{
    double value2;
    double value3;

    value2 = 2.362;
    value3 = 5;

    cout << fixed << setprecision(2);

    cout << value2 << endl;
    cout << VALUE_1 << endl;
    cout << value3 << endl;

return 0;
}

I tried the following fix and it works fine, but is there anything else that doesn't look so improvised? Or is this the intended method?

    cout << value_2 << endl;
    cout << setprecision (3) << value_1 << endl;
    cout << setprecision (2) << value_3 << endl;
yuidk
  • 23
  • 2
  • Not any truly fancier way, but see [Restore the state of std::cout after manipulating it](https://stackoverflow.com/questions/2273330/restore-the-state-of-stdcout-after-manipulating-it) in the general case. – dxiv Oct 01 '20 at 02:45

1 Answers1

0

I would probably do it by writing my own manipulator to at least combine the steps of setting fixed format and the width I wanted:

class fixed {
    int width;
public:
    fixed(int width) : width(width) {}

    friend std::ostream &operator<<(std::ostream &os, fixed const &f) { 
        return os << std::fixed << std::setw(width);
    }
};

Then you'd write out your numbers like:

std::cout << fixed(3) << value2 << '\n'
          << fixed(2) << VALUE_1 << '\n'
          << fixed(2) << value3 << '\n';

Admittedly, not a drastic improvement, but seems at least a little better to me.

Oh and avoid std::endl unless you really need it (which is pretty much never).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111