3

I'm doing some calculations, and the results are being save in a file. I have to output very precise results, near the precision of the double variable, and I'm using the iomanip setprecision(int) for that. The problem is that I have to put the setprecision everywhere in the output, like that:

func1() {
cout<<setprecision(12)<<value;
cout<<setprecision(10)<<value2;
}
func2() {
cout<<setprecision(17)<<value4;
cout<<setprecision(3)<<value42;
}

And that is very cumbersome. Is there a way to set more generally the cout fixed modifier?

Thanks

Ivan
  • 19,560
  • 31
  • 97
  • 141

2 Answers2

7

Are you looking for cout.precision ?

nc3b
  • 15,562
  • 5
  • 51
  • 63
1

In C++20 you'll be able to use std::format which gives you shortest decimal representation by default, so you won't loose precision even if you don't specify it manually. For example:

std::cout << std::format("{}", M_PI);

prints

3.141592653589793

If you need a fixed precision you can store it in a variable and reuse in multiple places:

int precision = 10;
std::cout << std::format("{:.{}}", value, precision);
vitaut
  • 49,672
  • 25
  • 199
  • 336