0

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
  • 1
    https://stackoverflow.com/questions/16605967/set-precision-of-stdto-string-when-converting-floating-point-values – Alexander Sobetskiy Sep 16 '22 at 05:28
  • 20 digits is more than you can meaningfully expect from a double. According to an old professor of mine, print that many and you'd be lying. We were warned that if we did that on a problem, we'd get a 0 for that problem. – Avi Berger Sep 16 '22 at 05:30
  • @AviBerger, 20 was just an example, thanks for the information though. – Faizan Ahmed Sep 16 '22 at 05:41

0 Answers0