3

I have search the web but couldn't find what I need.

Some people recommend using

streamsize ss = std::cout.precision();

but I couldn't get it to work.

How do I set a double value back to the original state after setprecision?

#include <iostream>
using namespace std;

int main() 
{
 double a;
 cout << "enter a double value: ";
 cin >> a;
 cout << "your value in 3 decimals is " << setprecision(3) << fixed << a << endl;
 cout << "your original value is " << a << endl;

 return 0;
 }

Obviously the code above will not return the original value of a.

My intended output is: if user enter 1.267432

your value in 3 decimals is 1.267
your original value is 1.267432
Tasmin
  • 41
  • 1
  • 4

2 Answers2

2

How do I set a double value back to the original state after setprecision?

To do so, you have to get the precision before you use setprecision(). In your question you already mentioned it by the following line:

streamsize ss = std::cout.precision();

but I couldn't get it to work.

Here how you use it:

streamsize ss = std::cout.precision();

double a = 1.267432;

std::cout << "a = " << a << '\n';

std::cout.precision (3);
std::cout << "a becomes = " << a << '\n';

std::cout.precision (ss);
std::cout << "Original a= " << a << '\n';

And the output will be like:

a = 1.26743

a becomes = 1.27

Original a= 1.26743

Reference: setprecision.

Run live.

Community
  • 1
  • 1
mazhar islam
  • 5,561
  • 3
  • 20
  • 41
  • This method does not work. For example, if user enter 1.42324, the outputs are 0.000 and 1.423 – Tasmin Oct 29 '15 at 06:46
  • 1
    @Tasmin, I edited the answer. Also I tested the code. It works exactly how you want. [Running code link](http://ideone.com/QWk5uJ). – mazhar islam Oct 29 '15 at 07:13
1

You can try like this:

#include <iomanip>
#include <iostream>

int main()
{
    double a = 1.267432;
    std::cout << std::fixed << std::showpoint;
    std::cout << std::setprecision(3);
    std::cout << a << endl;
    return 0;

}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • I tried this method multiple time before I posted the question, it just does not work. Which I do not understand why. – Tasmin Oct 29 '15 at 06:46