Convert double to string in C++ – (3 ways)

In this article, we will learn about three different ways to convert a double to a string in C++ i.e.

  1. Using std::to_string() function
  2. Using std::stingstream
  3. Using Boost’s lexical_cast() function.

Let’s discuss them one by one.

Convert double to string using to_string()

C++ provides a function std::to_string() for data type conversion. We can use this to convert a double to a string. For example,

#include <iostream>
#include <string>

using namespace std;

int main()
{
    double num = 324.671734;

    // Convert double to string
    string num_str = to_string(num);

    cout<<num_str<<endl;

    return 0;
}

Output:

324.671734

We passed a double value to the to_string() function, and it converted the given double to a string and returned the string object. It will keep the precision level as it is. If you want more control over the precision level of double while converting it to string, then look at the following technique using stringstream.

Convert double to string with specified precision using stringstream in C++

C++ provides a class stringstream, which provides a stream-like functionality. We can insert different types of elements in stringstream and get a final string object from the stream. We can use that to convert double to string. In the stream, we can also set the precision level of double-type elements before conversion. Check out this example,

#include <iostream>
#include <string>
#include<sstream> 

using namespace std;

int main()
{
    double num = 456.672891;

    stringstream stream;  

    // Set precision level to 3
    stream.precision(3);
    stream << fixed;
    
    // Convert double to string
    stream<<num;  
    string str  = stream.str();  

    cout<<str<<endl;

    return 0;
}

Output:

456.673

In the stringstream, we inserted a double to the stringstream, and then the stream converted the double to string. Also, as we set the precision level to 3, it rounded off the value to keep only three digits after the dot.

Convert double to string using boost::lexical_cast()

The C++ boost library, provides a template function for data type conversion. It helps to convert elements from one data type to another. We can use that to convert a double to string. For example,

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

using namespace std;
using namespace boost;

int main()
{
    double number = 458.673789;
    
    // Convert double to string using boost library
    string str = lexical_cast<string>(number);  
    
    cout<<str<<endl;

    return 0;
}

Output:

458.673789

Summary:

We learned about three different ways to convert a double value to a string in C++.

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top