Store The Result of Division of Two Doubles in a String up to a Particular Precision in C++

Viewed 17

The Question in brief:

How to print the result of a double division in a string with a certain precision.

The Description:

Suppose I want to store the result of a double division in a string, one way to do it would be like this:

double a = 22.0;
double b = 7.0;
double c = a / b;           // storing the result in temporary var
string str = to_string(c);  // the string to be printed
cout << str;                // this prints 3.142857

To print the number with a particular precision, I could simply use:

cout << setprecision(20) << c;  // this prints 3.1428571428571427937

Now I want to store this double with 20 precision in a string, I am not aware about any technique to do so.

This is my desired outcome:

string str = to_string(c); // the string to be printed
/*
    some operation with str here to make it print 
    upto 20 precision
*/
cout << str;               // this should print 3.1428571428571427937
0 Answers
Related