Convert float to String in C++

Convert float to String in C++

In this article we will discuss three different ways to convert float to string in C++.

Using ostringstream to convert float to string in C++

In this method we use 0stringstream to pass a float number to the buffer and then convert it into a string by using the str() method. setprecision(int n) function is also used with fixed to provide precision to floating numbers correct to decimal numbers passed as argument in the function. It is defined in the header.

Note: The string returned is only a temporary object and if other methods are called on the results, then it will yield a dangling pointer.

Code:

Output

After converting to string: 9.2300

Using to_string() function to convert float to string in C++

to_string() function can also be used to convert float to string and it is defined in the header. This function can be used to convert different numeric values to string data type. It is very easy to implement and it can take floating point numbers as a parameter and will return string type value.

Note: This function can return unexpected output because the number of significant digits in the string returned by it can be zero as well and it can be seen in code.

Code

Output

Enter the float number to convert to string: 58.25828
After Converting to String: 58.258282

Using Macro expression to convert float to string in C++

This method will work only for literal floating point numbers. In this method, preprocessor macros can be utilized to convert constant floating point number to string. In the coding part, we can see the right way to call the string variable constructor. We need #operator for STRING macro to convert float to string in C++.

Code:

Output

After converting to string: 9876.5412

If we define a constant floating point number as another macro expression, then we can use two-level macro to get the correct results.
Code:

Output

After converting to string: 9876.5412

Using lexical_cast method from the Boost libraries to convert float to String in C++

Boost library has a lexical_cast function which can be used to convert float to String.
Code:

Output

Enter the float number to convert to string: 23.228
After Converting to String: 23.228

Conclusion

In this article, we discussed three different ways to convert float to string in C++. In all the methods, we have to take care of a few things while using them.
Happy Learning!!

Was this post helpful?

Leave a Reply

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