mohitm's blog

By mohitm, history, 5 years ago, In English

Below is the code for a function returing a double value as string whose precision is 15(i.e. no. of digit after decimal should be 15)

Click here to see the execution on ide

#include <bits/stdc++.h>
using namespace std;

string doit(){

    cout<<setprecision(15)<<fixed;

    double val = 4444/21;

    // want to return it as string
    string ans = to_string(val);

    return ans;
}

int main() {

    string ans = doit();
    cout<<ans;
    return 0;
}

output is

211.000000

I want the output to contain 15 digits after decimal and it should be returned by the function and not use print/cout statement inside the function.

  • Vote: I like it
  • -9
  • Vote: I do not like it

»
5 years ago, # |
  Vote: I like it +3 Vote: I do not like it

double val = 4444/21.0; or double val = 4444.0/21; or double val = 4444/(double)21; or ...

4444 is the integer value, 21 is the integer value, so 4444/21 is the integer value too.

»
5 years ago, # |
  Vote: I like it +1 Vote: I do not like it

You can use string streams.

string doit() {
  double val = 4444.0/21;
  stringstream ss;
  ss << fixed << setprecision(15) << val;
  return ss.str();
}