Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting precision on std::cout in entire file scope - C++ iomanip

Tags:

c++

cout

iomanip

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

like image 201
Ivan Avatar asked Sep 03 '25 03:09

Ivan


2 Answers

Are you looking for cout.precision ?

like image 162
nc3b Avatar answered Sep 05 '25 20:09

nc3b


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);
like image 35
vitaut Avatar answered Sep 05 '25 19:09

vitaut