[c++] How do I convert a double into a string in C++?

I need to store a double as a string. I know I can use printf if I wanted to display it, but I just want to store it in a string variable so that I can store it in a map later (as the value, not the key).

This question is related to c++ string double

The answer is


// The C way:
char buffer[32];
snprintf(buffer, sizeof(buffer), "%g", myDoubleVar);

// The C++03 way:
std::ostringstream sstream;
sstream << myDoubleVar;
std::string varAsString = sstream.str();

// The C++11 way:
std::string varAsString = std::to_string(myDoubleVar);

// The boost way:
std::string varAsString = boost::lexical_cast<std::string>(myDoubleVar);

If you use C++, avoid sprintf. It's un-C++y and has several problems. Stringstreams are the method of choice, preferably encapsulated as in Boost.LexicalCast which can be done quite easily:

template <typename T>
std::string to_string(T const& value) {
    stringstream sstr;
    sstr << value;
    return sstr.str();
}

Usage:

string s = to_string(42.5);

Use to_string().
example :

#include <iostream>   
#include <string>  

using namespace std;
int main ()
{
    string pi = "pi is " + to_string(3.1415926);
    cout<< "pi = "<< pi << endl;

  return 0;
}

run it yourself : http://ideone.com/7ejfaU
These are available as well :

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

Normaly for this operations you have to use the ecvt, fcvt or gcvt Functions:

/* gcvt example */
#include <stdio.h>
#include <stdlib.h>

main ()
{
  char buffer [20];
  gcvt (1365.249,6,buffer);
  puts (buffer);
  gcvt (1365.249,3,buffer);
  puts (buffer);
  return 0;
}

Output:
1365.25
1.37e+003   

As a Function:

void double_to_char(double f,char * buffer){
  gcvt(f,10,buffer);
}

Herb Sutter has an excellent article on string formatting. I recommend reading it. I've linked it before on SO.


You could also use stringstream.


You may want to read my prior posting on SO. (Macro'ed version with a temporary ostringstream object.)

For the record: In my own code, I favor snprintf(). With a char array on the local stack, it's not that inefficient. (Well, maybe if you exceeded the array size and looped to do it twice...)

(I've also wrapped it via vsnprintf(). But that costs me some type checking. Yelp if you want the code...)


I would look at the C++ String Toolkit Libary. Just posted a similar answer elsewhere. I have found it very fast and reliable.

#include <strtk.hpp>

double pi = M_PI;
std::string pi_as_string  = strtk::type_to_string<double>( pi );

You could try a more compact style:

std::string number_in_string;

double number_in_double;

std::ostringstream output;

number_in_string = (dynamic_cast< std::ostringstream*>(&(output << number_in_double <<

std::endl)))->str(); 

Heh, I just wrote this (unrelated to this question):

string temp = "";
stringstream outStream;
double ratio = (currentImage->width*1.0f)/currentImage->height;
outStream << " R: " << ratio;
temp = outStream.str();

/* rest of the code */

The Standard C++11 way (if you don't care about the output format):

#include <string>

auto str = std::to_string(42.5); 

to_string is a new library function introduced in N1803 (r0), N1982 (r1) and N2408 (r2) "Simple Numeric Access". There are also the stod function to perform the reverse operation.

If you do want to have a different output format than "%f", use the snprintf or ostringstream methods as illustrated in other answers.


Take a look at sprintf() and family.


I would look at the C++ String Toolkit Libary. Just posted a similar answer elsewhere. I have found it very fast and reliable.

#include <strtk.hpp>

double pi = M_PI;
std::string pi_as_string  = strtk::type_to_string<double>( pi );

sprintf is okay, but in C++, the better, safer, and also slightly slower way of doing the conversion is with stringstream:

#include <sstream>
#include <string>

// In some function:
double d = 453.23;
std::ostringstream os;
os << d;
std::string str = os.str();

You can also use Boost.LexicalCast:

#include <boost/lexical_cast.hpp>
#include <string>

// In some function:
double d = 453.23;
std::string str = boost::lexical_cast<string>(d);

In both instances, str should be "453.23" afterward. LexicalCast has some advantages in that it ensures the transformation is complete. It uses stringstreams internally.


Herb Sutter has an excellent article on string formatting. I recommend reading it. I've linked it before on SO.


If you use C++, avoid sprintf. It's un-C++y and has several problems. Stringstreams are the method of choice, preferably encapsulated as in Boost.LexicalCast which can be done quite easily:

template <typename T>
std::string to_string(T const& value) {
    stringstream sstr;
    sstr << value;
    return sstr.str();
}

Usage:

string s = to_string(42.5);

// The C way:
char buffer[32];
snprintf(buffer, sizeof(buffer), "%g", myDoubleVar);

// The C++03 way:
std::ostringstream sstream;
sstream << myDoubleVar;
std::string varAsString = sstream.str();

// The C++11 way:
std::string varAsString = std::to_string(myDoubleVar);

// The boost way:
std::string varAsString = boost::lexical_cast<std::string>(myDoubleVar);

Heh, I just wrote this (unrelated to this question):

string temp = "";
stringstream outStream;
double ratio = (currentImage->width*1.0f)/currentImage->height;
outStream << " R: " << ratio;
temp = outStream.str();

/* rest of the code */

// The C way:
char buffer[32];
snprintf(buffer, sizeof(buffer), "%g", myDoubleVar);

// The C++03 way:
std::ostringstream sstream;
sstream << myDoubleVar;
std::string varAsString = sstream.str();

// The C++11 way:
std::string varAsString = std::to_string(myDoubleVar);

// The boost way:
std::string varAsString = boost::lexical_cast<std::string>(myDoubleVar);

You could try a more compact style:

std::string number_in_string;

double number_in_double;

std::ostringstream output;

number_in_string = (dynamic_cast< std::ostringstream*>(&(output << number_in_double <<

std::endl)))->str(); 

The problem with lexical_cast is the inability to define precision. Normally if you are converting a double to a string, it is because you want to print it out. If the precision is too much or too little, it would affect your output.


sprintf is okay, but in C++, the better, safer, and also slightly slower way of doing the conversion is with stringstream:

#include <sstream>
#include <string>

// In some function:
double d = 453.23;
std::ostringstream os;
os << d;
std::string str = os.str();

You can also use Boost.LexicalCast:

#include <boost/lexical_cast.hpp>
#include <string>

// In some function:
double d = 453.23;
std::string str = boost::lexical_cast<string>(d);

In both instances, str should be "453.23" afterward. LexicalCast has some advantages in that it ensures the transformation is complete. It uses stringstreams internally.


The problem with lexical_cast is the inability to define precision. Normally if you are converting a double to a string, it is because you want to print it out. If the precision is too much or too little, it would affect your output.


You could also use stringstream.


Herb Sutter has an excellent article on string formatting. I recommend reading it. I've linked it before on SO.


sprintf is okay, but in C++, the better, safer, and also slightly slower way of doing the conversion is with stringstream:

#include <sstream>
#include <string>

// In some function:
double d = 453.23;
std::ostringstream os;
os << d;
std::string str = os.str();

You can also use Boost.LexicalCast:

#include <boost/lexical_cast.hpp>
#include <string>

// In some function:
double d = 453.23;
std::string str = boost::lexical_cast<string>(d);

In both instances, str should be "453.23" afterward. LexicalCast has some advantages in that it ensures the transformation is complete. It uses stringstreams internally.


Take a look at sprintf() and family.


If you use C++, avoid sprintf. It's un-C++y and has several problems. Stringstreams are the method of choice, preferably encapsulated as in Boost.LexicalCast which can be done quite easily:

template <typename T>
std::string to_string(T const& value) {
    stringstream sstr;
    sstr << value;
    return sstr.str();
}

Usage:

string s = to_string(42.5);

Use to_string().
example :

#include <iostream>   
#include <string>  

using namespace std;
int main ()
{
    string pi = "pi is " + to_string(3.1415926);
    cout<< "pi = "<< pi << endl;

  return 0;
}

run it yourself : http://ideone.com/7ejfaU
These are available as well :

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

You can use std::to_string in C++11

double d = 3.0;
std::string str = std::to_string(d);

You could also use stringstream.


Take a look at sprintf() and family.


Heh, I just wrote this (unrelated to this question):

string temp = "";
stringstream outStream;
double ratio = (currentImage->width*1.0f)/currentImage->height;
outStream << " R: " << ratio;
temp = outStream.str();

/* rest of the code */

Normaly for this operations you have to use the ecvt, fcvt or gcvt Functions:

/* gcvt example */
#include <stdio.h>
#include <stdlib.h>

main ()
{
  char buffer [20];
  gcvt (1365.249,6,buffer);
  puts (buffer);
  gcvt (1365.249,3,buffer);
  puts (buffer);
  return 0;
}

Output:
1365.25
1.37e+003   

As a Function:

void double_to_char(double f,char * buffer){
  gcvt(f,10,buffer);
}

sprintf is okay, but in C++, the better, safer, and also slightly slower way of doing the conversion is with stringstream:

#include <sstream>
#include <string>

// In some function:
double d = 453.23;
std::ostringstream os;
os << d;
std::string str = os.str();

You can also use Boost.LexicalCast:

#include <boost/lexical_cast.hpp>
#include <string>

// In some function:
double d = 453.23;
std::string str = boost::lexical_cast<string>(d);

In both instances, str should be "453.23" afterward. LexicalCast has some advantages in that it ensures the transformation is complete. It uses stringstreams internally.


You may want to read my prior posting on SO. (Macro'ed version with a temporary ostringstream object.)

For the record: In my own code, I favor snprintf(). With a char array on the local stack, it's not that inefficient. (Well, maybe if you exceeded the array size and looped to do it twice...)

(I've also wrapped it via vsnprintf(). But that costs me some type checking. Yelp if you want the code...)


You can convert any thing to anything using this function:

template<class T = std::string, class U>
T to(U a) {
    std::stringstream ss;
    T ret;
    ss << a;
    ss >> ret;
    return ret;
};

usage :

std::string str = to(2.5);
double d = to<double>("2.5");

You could also use stringstream.


Herb Sutter has an excellent article on string formatting. I recommend reading it. I've linked it before on SO.


If you use C++, avoid sprintf. It's un-C++y and has several problems. Stringstreams are the method of choice, preferably encapsulated as in Boost.LexicalCast which can be done quite easily:

template <typename T>
std::string to_string(T const& value) {
    stringstream sstr;
    sstr << value;
    return sstr.str();
}

Usage:

string s = to_string(42.5);

You can convert any thing to anything using this function:

template<class T = std::string, class U>
T to(U a) {
    std::stringstream ss;
    T ret;
    ss << a;
    ss >> ret;
    return ret;
};

usage :

std::string str = to(2.5);
double d = to<double>("2.5");

Heh, I just wrote this (unrelated to this question):

string temp = "";
stringstream outStream;
double ratio = (currentImage->width*1.0f)/currentImage->height;
outStream << " R: " << ratio;
temp = outStream.str();

/* rest of the code */

You can use std::to_string in C++11

double d = 3.0;
std::string str = std::to_string(d);

// The C way:
char buffer[32];
snprintf(buffer, sizeof(buffer), "%g", myDoubleVar);

// The C++03 way:
std::ostringstream sstream;
sstream << myDoubleVar;
std::string varAsString = sstream.str();

// The C++11 way:
std::string varAsString = std::to_string(myDoubleVar);

// The boost way:
std::string varAsString = boost::lexical_cast<std::string>(myDoubleVar);

The Standard C++11 way (if you don't care about the output format):

#include <string>

auto str = std::to_string(42.5); 

to_string is a new library function introduced in N1803 (r0), N1982 (r1) and N2408 (r2) "Simple Numeric Access". There are also the stod function to perform the reverse operation.

If you do want to have a different output format than "%f", use the snprintf or ostringstream methods as illustrated in other answers.


You may want to read my prior posting on SO. (Macro'ed version with a temporary ostringstream object.)

For the record: In my own code, I favor snprintf(). With a char array on the local stack, it's not that inefficient. (Well, maybe if you exceeded the array size and looped to do it twice...)

(I've also wrapped it via vsnprintf(). But that costs me some type checking. Yelp if you want the code...)


Examples related to c++

Method Call Chaining; returning a pointer vs a reference? How can I tell if an algorithm is efficient? Difference between opening a file in binary vs text How can compare-and-swap be used for a wait-free mutual exclusion for any shared data structure? Install Qt on Ubuntu #include errors detected in vscode Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error How to fix the error "Windows SDK version 8.1" was not found? Visual Studio 2017 errors on standard headers How do I check if a Key is pressed on C++

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to double

Round up double to 2 decimal places Convert double to float in Java Float and double datatype in Java Rounding a double value to x number of decimal places in swift How to round a Double to the nearest Int in swift? Swift double to string How to get the Power of some Integer in Swift language? Difference between int and double How to cast the size_t to double or int C++ How to get absolute value from double - c-language