2 minute read

Introduction

In this tutorial, you will learn how to convert a float (such as 51.31) to a string format in the C++ programming language. The to_string function from the std library is used to convert a float to a string. The function is defined as follows:

For instance, given a float such as 51.31. Then, we would like to get a string like “51.31”

Method #1: Using std::to_string()

We can use the to_string() function to convert a float to a string. It is a function from the std library, so we will need to import the following libraries into the header area of our code.

For instance:

#include <string> //Add this
#include <iostream> //Add this

int main()
{
    float x = 412.524;
	std::string myString = std::to_string(x);
	std::cout << "myString is: " << myString << std::endl; //Returns "myString is: 412.524"
	return 0;
}

NOTE: Do not forget to include the string library, otherwise we may get the std::to_string is not a member of std error.

It is important to note that accuracy problems might appear when working with float-to-string convertions with the std::to_string() function. For instance, some C++ compilers might return 412.523987 instead of 412.524.

Method #2: Using std::stringstream

The std::stringstream function can be used to convert float types into strings, however it is a slightly longer function.

To start, given our float x, we need to define a stringstream like:

float x = 412.524;
std::stringstream myStream;

Next, we define myStream as:

myStream << x;

Finally, we need to convert our stringstream object to a string:

std::string resultString = myStream.str();

Resulting code:

#include <sstream> //Add this to use stringstream
#include <iostream> //Add this to use cout

int main(){
    float x = 412.5241;
    std::stringstream myStream;
    myStream << x;
    std::string resultString = myStream.str();
    std::cout << resultString << std::endl; //Prints out 412.524
    return 0;
}

Important: Make sure to use the sstream and iostream libraries to run the code above successfully.

Note that, by default myStream only saves 3 decimal points.

We can customize this to any value by using the std::setprecision(n) function, where n is the amount of decimal points that we want to save. For instance:

#include <sstream>
#include <iostream>
#include <iomanip>

int main(){
    float x = 412.5241;
    std::stringstream myStream;
    myStream << std::fixed << std::setprecision(4) << x;
    std::string resultString = myStream.str();
    std::cout << resultString << std::endl; //Prints out 412.5241
    return 0;
}

References

Read more about the std::to_string function here: https://en.cppreference.com/w/cpp/string/basic_string/to_string Read more about the std::to_string function here: https://www.cplusplus.com/reference/sstream/stringstream/