C++ Program For Double to String Conversion
Last Updated :
26 Jul, 2022
Here, we will build a C++ program for double to string conversion using various methods i.e.
- Using to_string
- Using stringstream
- Using sprintf
- Using lexical_cast
We will keep the same input in all the mentioned approaches and get an output accordingly.
Input:
n = 456321.7651234
Output:
string: 456321.7651234
1. Using to_string
In C++, use std::to string to convert a double to a string. The required parameter is a double value, and a string object containing the double value as a sequence of characters is returned.
C++
#include <iostream>
#include <string.h>
using namespace std;
int main()
{
double n = 456321.7651234;
string str = to_string(n);
cout << "String is: " << str;
return 0;
}
|
Output
String is: 456321.765123
2. Using stringstream
A double can also be converted into a string in C++ in different ways depending on our requirements using ostringstream.
C++
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main()
{
ostringstream s;
double n = 2332.43;
s << n;
string str = s.str();
cout << "String is:" << str;
return 0;
}
|
3. Using sprintf
By specifying the precision in sprintf, we can convert double to string or character array with custom precision. We can use sprintf to add extra text (as required) to the string at the same time.
C++
#include <cstring>
#include <iostream>
#include <string>
#define Max_Digits 10
using namespace std;
int main()
{
double N = 1243.3456;
char str[Max_Digits + sizeof ( char )];
std:: sprintf (str, "%f" , N);
std:: printf ( "string is: %s \n" , str);
return 0;
}
|
Output
string is: 1243.345600
4. Using lexical_cast
The lexical cast is one of the best ways to convert double to string.
C++
#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>
using namespace std;
int main()
{
double n = 432.12;
string str = boost::lexical_cast<string>(n);
cout << "string is:" << str;
return 0;
}
|
Share your thoughts in the comments
Please Login to comment...