Function not returing specified precision for a double value?

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 her 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.

You can use sprintf as here.

1 Like

@dhirajfx3 Thanks a lot bro :smiley:

#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;

string doit(){

    stringstream out;
    out<<setprecision(15)<<fixed;

    double val = 4444/21;

    // want to return it as string
    out << val;

    return out.str();
}

int main() {

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

Is this question from some ongoing contest??

@invincible1212 nope.