Setting precision on std::cout in entire file scope - C++ iomanip
I'm doing some ca开发者_如何学JAVAlculations, 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
Are you looking for cout.precision ?
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);
精彩评论