c++ - How to format doubles in the following way? -


i using c++ , format doubles in following obvious way. have tried playing 'fixed' , 'scientific' using stringstream, unable achieve desired output.

double d = -5; // print "-5" double d = 1000000000; // print "1000000000" double d = 3.14; // print "3.14" double d = 0.00000000001; // print "0.00000000001" // floating point error acceptable: double d = 10000000000000001; // print "10000000000000000" 

as requested, here things i've tried:

#include <iostream> #include <string> #include <sstream> #include <iomanip>  using namespace std;  string obvious_format_attempt1( double d ) {     stringstream ss;     ss.precision(15);     ss << d;     return ss.str(); }  string obvious_format_attempt2( double d ) {     stringstream ss;     ss.precision(15);     ss << fixed;     ss << d;     return ss.str(); }  int main(int argc, char *argv[])  {     cout << "attempt #1" << endl;     cout << obvious_format_attempt1(-5) << endl;     cout << obvious_format_attempt1(1000000000) << endl;     cout << obvious_format_attempt1(3.14) << endl;     cout << obvious_format_attempt1(0.00000000001) << endl;     cout << obvious_format_attempt1(10000000000000001) << endl;      cout << endl << "attempt #2" << endl;     cout << obvious_format_attempt2(-5) << endl;     cout << obvious_format_attempt2(1000000000) << endl;     cout << obvious_format_attempt2(3.14) << endl;     cout << obvious_format_attempt2(0.00000000001) << endl;     cout << obvious_format_attempt2(10000000000000001) << endl;      return 0; } 

that prints following:

attempt #1 -5 1000000000 3.14 1e-11 1e+16  attempt #2 -5.000000000000000 1000000000.000000000000000 3.140000000000000 0.000000000010000 10000000000000000.000000000000000 

there no way program know how format numbers in way describing, unless write code analyze numbers in way - , can quite hard.

what required here knowing input format in source code, , that's lost compiler converts decimal input source code binary form store in executable file.

one alternative may work output stringstream, , modify output strip trailing zeros. this:

string obvious_format_attempt2( double d ) {     stringstream ss;     ss.precision(15);     ss << fixed;     ss << d;     string res = ss.str();     // have dot?     if ((string::size_type pos = res.rfind('.')) != string::npos)     {        while(pos > 0 && (res[pos] == '0' || res[pos] == '.')        {            pos--;        }        res = res.substr(pos);     }     return res; } 

i haven't tired it, rough sketch, should work. caveats if have 0.1, may print 0.09999999999999285 or such, becuase 0.1 can not represented in exact form binary.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -