In this article, we will learn about three different ways to convert a float 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 float to string using to_string()

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

#include <iostream>
#include <string>

using namespace std;

int main()
{
    float number = 1024.671734;

    // Convert float to string
    string num_str = to_string(number);

    cout<<num_str<<endl;

    return 0;
}

Output:

1024.671753

We passed a float value to the to_string() function, and it converted the given float 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 float while converting it to string, then look at the following technique using stringstream.

Convert float 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 float to string. In the stream, we can also set the precision level of float-type elements before conversion. Check out this example,

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

using namespace std;

int main()
{
    float number = 1024.671734;

    stringstream stream;  

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

    cout<<str<<endl;

    return 0;
}

Output:

1024.672

In the stringstream, we inserted a float to the stringstream, and then the stream converted the float 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 float 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 float to string. For example,

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

using namespace std;
using namespace boost;

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

    return 0;
}

Output:

1024.67175

Summary:

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