Reputation: 21
I was of the opinion that setprecision doesnt change the value in variable itself. Also, when you attach setprecision to cout, it sticks with it only once. However, when I run code to verify, it doesnt work.
Consider the following code snippet:
int main()
{
double x = 9.87654321;
cout << setprecision(3) << fixed << x <<endl; //Returns 9.877 as it should
cout << x << endl; //Returns truncated value 9.877 again though it shouldnt.
return 0;
}
Interesting part is, if we replace cout << x << endl;
by a line setting precision to say 7, then it DOES display the correct value. Can anyone please explain this phenomenon?
Upvotes: 2
Views: 2117
Reputation: 6586
Other answers have indicated the problem. One possible solution is to use the Boost I/O Stream state saver library to do the work of saving the I/O stream formatting state and restoring it at the appropriate time.
Upvotes: 0
Reputation: 791699
You don't reset the precision to the original value so it's just using 3 as the precision value for both output operations.
If you want to restore the original precision then you need to save it. The initial value for standard ostream
s is 6 which may not be accurate enough for many purposes.
int main()
{
double x = 9.87654321;
size_t save_prec = cout.precision();
cout << setprecision(3) << fixed << x <<endl;
cout.precision(save_prec);
cout << x << endl;
return 0;
}
Upvotes: 5
Reputation: 5425
It sets the precision of the output stream, not x
, meaning after the call to setprecision(3)
, cout
outputs all numbers with precision of 3.
http://www.cplusplus.com/reference/iostream/manipulators/setprecision/
Try this, which will show that x has not changed.
int main()
{
double x = 9.87654321;
cout << setprecision(3) << fixed << x <<endl; //Returns 9.877 as it should
cerr << x << endl; //Returns 9.87654 to stderr
return 0;
}
Upvotes: 0