Get precision of cout
Asked Answered
O

2

5

I can set precision of cout output using

cout.precision(precision_value);

how can I get the precision value, which is used by cout already? I can't find any other related function in cout description.

The related problem I faced is how can I change cout precision for some part of a code only (so it need to be reset afterwards to exact previous value).

I tryed:

//save original cout flags
std::ios_base::fmtflags coutFlags = cout.flags();

cout.precision(1);
cout.setf(ios::fixed);

 // code

cout.flags(coutFlags);

but this doens't work.

Omen answered 4/12, 2013 at 11:28 Comment(3)
why not use a variable and change it each tim?Tug
en.cppreference.com/w/cpp/io/ios_base/precisionCinematography
cout.setf(ios::fixed); overwrites all flags, and not just the flag of interest. I made the same mistake recently: istringstream not honoring base?.Shull
D
12

The function is overloaded. Both overloads return the precision that was set before the call to the function. cout.precision() may be what you want to query it.

To save it and set it back later:

auto old_precision = cout.precision(temp_precision);
// do stuff
cout.precision(old_precision);
Dysphonia answered 4/12, 2013 at 11:32 Comment(1)
oh, I totally missed the return value. Was looking for another function. Thanks.Omen
H
4

With the function precision().

int main() {
  std::cout << std::cout.precision() << std::endl;
  return 0;
}
Hershel answered 4/12, 2013 at 11:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.