Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

string

double

People also ask

Is double %D in C?

%d stands for decimal and it expects an argument of type int (or some smaller signed integer type that then gets promoted). Floating-point types float and double both get passed the same way (promoted to double ) and both of them use %f .

How do I convert a double to a string in C++?

A double can be converted into a string in C++ using std::to_string. The parameter required is a double value and a string object is returned that contains the double value as a sequence of characters.

Can we convert float to string in C?

gcvt() | Convert float value to string in C This function is used to convert a floating point number to string. Syntax : gcvt (float value, int ndigits, char * buf); float value : It is the float or double value. int ndigits : It is number of digits.


// 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 boost (tm) way:

std::string str = boost::lexical_cast<std::string>(dbl);

The Standard C++ way:

std::ostringstream strs;
strs << dbl;
std::string str = strs.str();

Note: Don't forget #include <sstream>


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 can use std::to_string in C++11

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

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);