+ 1

How to use std::setprecision in C++

I'm experimenting with std::setprecision, is good to say how many decimals you want to show but... I have a problem. I realized that also affects other variables and not only the variable that I want the precision. Float a = 2.15111; Float b = 3.15222; Cout << std::fixed << std:: setprecision(2) << a; // 2.15 Cout << b; // 3.15 In the above code, I want to implement the precision only to variable a, but it also affects to variable b... How can I fix that? I want to print b with the default precision.

24th Jan 2019, 7:07 AM
Eduardo Perez Regin
Eduardo Perez Regin - avatar
5 ответов
+ 8
I found this funny behaviour with std::setprecision, when I pass a negative value (-1) as argument it appears to reset the previous setting for std::setprecision (not the std::fixed probably), I'm not sure if it violates any rules, but even though it works, I think it's not a good practice : ) #include <iostream> #include <iomanip> int main() { float a = 2.15111; float b = 3.15222; std::cout << std::fixed << std:: setprecision(2) << a << std::endl; // 2.15 std::cout << std::setprecision(-1) << b; // 3.152220 return 0; }
24th Jan 2019, 8:58 AM
Ipang
+ 5
The original precision can be obtained prior to setprecision, via std::cout.precision(). You can then use std::defaultfloat to reset to default floating point notation: http://www.cplusplus.com/reference/ios/defaultfloat/ float a = 2.15111, b = 2.15112; std::streamsize ss = std::cout.precision(); // original io formatting std::cout << a << " " << b << "\n"; // edited std::cout << std::fixed << std::setprecision(2) << a << " " << b; // restored std::cout << std::defaultfloat << std::setprecision(ss) << a << " " << b; However, resetting the entire state of std::cout may be an even better idea, but I haven't figured out how to do so for precision with resetiosflags(), since precision does not appear to be a flag, and is by default 6. http://www.cplusplus.com/reference/iomanip/resetiosflags/
24th Jan 2019, 7:37 AM
Hatsy Rei
Hatsy Rei - avatar
+ 4
Thanks Hatsy Rei, I guess your example was the way to go, I'd probably wouldn't use the negative value in the end anyways, kinda illogical : )
24th Jan 2019, 3:25 PM
Ipang
+ 2
Ipang Interesting observations, and presumably accurate too. :> https://stackoverflow.com/questions/1957532/negative-precision-values-in-ostream
24th Jan 2019, 2:05 PM
Hatsy Rei
Hatsy Rei - avatar
+ 1
I see how many extra steps you need to do to return again the default precision, I think If I only want to set how many decimals I want to show only for one variable, maybe the old printf is not a bad option... Thank you so much to everyone!
24th Jan 2019, 11:14 PM
Eduardo Perez Regin
Eduardo Perez Regin - avatar