Converting a precision double to a string

17,916

Solution 1

std::stringstream str;
str << fixed << setprecision( 15 ) << yournumber;

You may also be interested in the scientific format flag.

C++11 also has a few interesting functions std::to_string which you may want to check out!

Solution 2

What's wrong with the standard way?

std::stringstream ss;
ss << val;
std::string s = ss.str();

Additionally, C++11 allows:

std::string s = std::to_string(val);

If you need performance you might find that the memory allocations involved above are too expensive, in which case you could resort to snprintf, the deprecated strstream, or perhaps direct use of the num_put facet. For example:

char c[30];
std::snprintf(c,sizeof c,"%e",val);

Solution 3

You will find that the double value is not as precise as you think. It only contains 53 bits of precision, or about 15-17 digits; after that it starts rounding each result. Your number requires much more precision than that if you want an exact answer, 92 digits actually or 364 bits.

Share:
17,916
Marobri
Author by

Marobri

Updated on June 05, 2022

Comments

  • Marobri
    Marobri over 1 year

    I have a large number in c++ stored as a precise double value (assuming the input 'n' is 75): 2.4891e+109

    Is there any way to convert this to a string or an array of each individual digit?

    Here's my code so far, although it's not entirely relevant to the question:

    int main(){
    
        double n = 0; 
        cout << "Giz a number: ";
        cin >> n;
        double val = 1;
        for(double i = 1; i <= n; i++){
            val = val * i;
        }
        //Convert val to string/array here?
    }
    
  • Shahbaz
    Shahbaz over 11 years
    how does that convert val to a string/array?!
  • DomTomCat
    DomTomCat over 6 years
    I like the hint to C++11. However I dislike that std::to_string doesn't offer flexibility (precision etc)