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

C++ProgrammingServer Side Programming

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.

A program that demonstrates this in C++ is given as follows.

Example

 Live Demo

#include <iostream>
#include <string.h>
using namespace std;
int main() {
   double d = 238649.21316934;
   string s = to_string(d);
   cout << "Conversion of double to string: " << s;
   return 0;
}

Output

The output of the above program is as follows.

Conversion of double to string: 238649.213169

Now let us understand the above program.

A variable d of double type is initialized with a value 238649.21316934. This double value is converted to a string using to_string. Finally this is displayed. The code snippet that shows this is as follows.

double d = 238649.21316934;
string s = to_string(d);
cout << "Conversion of double to string: " << s;
raja
Published on 22-Nov-2018 12:17:24
Advertisements