How To Convert Float To String In C++

In computer programming, we frequently require changing one data type to another. We might need to convert a floating-point value to a string in C++ at some time.

This may be helpful in a number of circumstances, which includes formatting output or saving data to a file. The several methods for converting a float to a string in C++ will be covered in this article along with examples.

Why is there a need to know how to convert float to string in c++

There are many reasons for which you may need to convert float to string in c++. These reasons include:

  • Formatting the output: To limit the amount of decimal places, leading zeros, etc. when printing floating-point numbers to the console or a file, it is frequently required to format the output as a string.
  • Interoperability with other programs: In many circumstances, other programmes or systems may need input or output in the form of strings.
  • Data storage and serialisation: In order to assure compliance with the data storage format, it is frequently required to transform float values to strings prior to saving them to a file or database.
  • Debugging and logging: Converting float values to strings for output to the console or a log file might be helpful while debugging or logging a C++ programme.
  • Localization: To enable translation of decimal separators and other formatting norms, it is frequently necessary to format float numbers as strings when designing a multilingual application.

Approaches on how to convert float to string in c++

Numerous approaches are present on how to change float to string in c++. There are some approaches listed and discussed below.

  • Approach-1: Using std::ostringstream
  • Approach-2: Using sprintf() function
  • Approach-3: Using std::to_string() function
  • Approach-4: Using stringstream

Lets dive in details for each approach.

Approach-1: Using std::ostringstream

The std::ostringstream class in C++ can be used to convert a float to a string. A floating-point value can be inserted into an ostringstream object using the << operator, and it can then be converted to a string using the str() function.

Algorithm:

  1. Create an object called ostringstream.
  2. To add the float value to the ostringstream object, use the << operator.
  3. To get the resulting string representation of the float value, use the str() method.

Code:

#include <iostream>
#include <sstream>
using namespace std;

int main() {
   float f = 3.141592653589793;
   ostringstream ss; 
   //initiating the object ss 
   ss << f;  
   //using the << operator to insert the float value to the object
   string str = ss.str(); 
   //using the object ss to call the str() function
   cout << "Float value converted to string: " << str << endl;
   return 0;
}

Output:

Float value converted to string: 3.14159

Explanation:

  1. In this example, we first declare the float variable “f” and set its initial value to pi.
  2. Then, we use the << operator to put the value of “f” into an ostringstream object that we have declared as “ss”.
  3. To obtain the converted string value, we then execute the str() function on the ostringstream object.
  4. Lastly, we use cout to print the string value to the console.

Approach-2: Using sprintf() function

Using the sprintf() function is another method for C++ to convert a float to a string. To write formatted output to a string, use the sprintf() function from the standard library.

Algorithm:

  1. Declare a char array with enough space to hold the finished string.
  2. In order to convert the float value to a string and store it in the char array, use the sprintf() method with the necessary format specifier.
  3. Use the resulting char array to represent the float value in a string as needed.

Code:

#include <iostream>
#include <cstdio>
using namespace std;

int main() {
   float f = 3.141592653589793;
   char buffer[50];
   //declaring the char array
   sprintf(buffer, "%.5f", f);
   //formatting and storing in the array using the sprint() function
   string str(buffer);
   //type converting into string
   cout << "Float value converted to string: " << str << endl;
   return 0;
}

Output:

Float value converted to string: 3.14159

Explanation:

  1. In this example, we first declare the float variable “f” and set its initial value to pi.
  2. The string value is then declared to be stored in a character array “buffer” with a capacity of 50.
  3. Then, we write the formatted output to the buffer array using the sprintf() method.
  4. The float is transformed into a string with five decimal places using the “%.5f” format specifier.
  5. Lastly, we use cout to print the buffer array as a string to the console.

Approach-3: Using std::to_string() function

The third approach is to use  the std::to_string() function for converting a float to a string in C++. A standard library method called to string() transforms a numeric value into a string representation.

Algorithm:

  1. Call the std::to_string() function, passing in the float value to be converted.
  2. The float value’s string representation will be returned by the function.

Code:

#include <iostream>
#include <string>
using namespace std;

int main() {
   float f = 3.141592653589793;
   string str = to_string(f);
   //converting the float into string  value using the to_string inbuilt function
   cout << "Float value converted to string: " << str << endl;
   //printing the converted value to the console
   return 0;
}

Output:

Float value converted to string: 3.141593

Explanation:

  1. In this example, we first declare the “f” float variable and set its initial value to pi.
  2. After that, we convert the float to a string using the std::to string() method and save the outcome in the “str” string variable.
  3. The string value is then output to the console using cout.

Approach-4: Using stringstream

Use of the stringstream class is the fourth method for converting a float to a string in C++. The str() function can be used to turn a float value into a string after being inserted into a stringstream object using the << operator.

Algorithm:

  1. Create an object called stringstream.
  2. To add the float value to the stringstream object, use the << operator.
  3. To get the resulting string representation of the float value, use the str() method.

Code:

#include <iostream>
#include <sstream>
using namespace std;

int main() {
   float f = 3.141592653589793;
   stringstream ss;
   //creating the object
   ss << f;
   //adding the float value using the << operator
   string str = ss.str();
   //converting float value into the string
   cout << "Float value converted to string: " << str << endl;
   //printing the value to the console
   return 0;
}

Output:

Float value converted to string: 3.14159

Explanation:

  1. In this example, we first declare the float variable “f” and set its initial value to pi.
  2. Then, we declare a stringstream object called “ss” and use the operator to insert the value of “f.”
  3. To obtain the converted string value, we then execute the str() function on the stringstream object.
  4. Lastly, we use cout to print the string value to the console.

Best Approach- Using std::to_string() function

The std::to_string() function is the most practical and effective technique to convert a float to a string in C++ out of the four methods discussed above. Here are the reasons why:

  1. Simplicity: The easiest and most direct approach to convert a float to a string is to use the std::to_string() function.
  2. Efficiency: std::to_string() is an extremely effective function. It does away with the requirement for a second buffer when using the sprintf() method.
  3. Automatic rounding: In many circumstances, the std::to_string() function comes in quite handy because it automatically rounds the float value to the next decimal place.
  4. Decimal places do not need to be specified: The number of decimal places to be included in the output string must be specified when using other methods like sprintf() or stringstream.
  5. Standardisation: The std::to_string() method is a common and well-known standard library function among other programmers.

Sample Problems on converting float to string in c++

Sample Problem-1: Using Approach-1

Problem Definition: Priya wants to write a C++ program that calculates the area of a circle with radius 5.5 and outputs the result as a string with 2 decimal places. Help Priya to write the program.

Solution: The code to resolve this issue using the std::ostringstream method is as follows:

Code:

#include <iostream>
#include <sstream>
#include <cmath>

int main() {
    const float PI = 3.14159;
    const float radius = 5.5;
    const float area = PI * pow(radius, 2);
    //calculating the are of the circle
 
    std::ostringstream ss;
    //creating the object of the ostringstream

    ss << std::fixed << std::setprecision(2) << area;
    //setting the number of decimal places

    std::cout << "The area of the circle is: " << ss.str() << std::endl;
    
    return 0;
}

Output:

The area of the circle is: 95.03

Code Explanation:

  • Using the formula A = r2, the software determines the area of a circle with a radius of 5.5.
  • The object ss of type ostringstream is declared.
  • Using the std::fixed and std::setprecision() functions, the area value is inserted into the ostringstream object with a fixed precision of 2 decimal places using the operator.
  • The str() function is used to extract the resultant string from the ostringstream object, and std::cout is used to print the string.

Sample Problem-2: Using Approach-2

Problem Definition: Write a program that calculates the square root of a positive integer using the Babylonian method and outputs the result as a string with exactly 6 decimal places.

Solution: The code to resolve this issue using the sprintf() method is as follows:

Code:

#include <cstdio>
#include <cmath>
#include <cstring>

int main() {
    int num;
    printf("Enter a positive integer: ");
    scanf("%d", &num);
   
    double guess = num / 2.0;
    double epsilon = 0.000001;
    double diff = num;
   
    while (diff > epsilon) {
        double new_guess = (guess + num / guess) / 2.0;
        diff = std::abs(guess - new_guess);
        guess = new_guess;
    }
   
    char str[50];
    sprintf(str, "%.6f", guess);
   
    printf("The square root of %d is: %s\n", num, str);
   
    return 0;
}

Output:

Enter a positive integer: 12345
The square root of 12345 is: 111.108055

Code Explanation:

  • The application requests a positive integer from the user and reads it using scanf().
  • Half of the input value serves as the initial square root guess.
  • Epsilon is set to be 0.000001.
  • Until the gap between the guess and the new guess is smaller than the epsilon value, a loop is run.
  • The Babylonian technique formula is used to determine a new guess within the loop: (guess + num / guess) / 2.0.
  • std::abs is used to calculate the difference between the guess and the new guess ().
  • For the following iteration, the guess is updated with the new guess.
  • The result of the loop is then saved in a char array called str using sprintf() and converted to a string with precisely 6 decimal places.
  • The output of the programme includes both the input value and the resultant string.

Sample Problem-3: Using Approach-3

Problem Definition: Harish wants to write a program that calculates the sum of two floating-point numbers and outputs the result as a string. Therefore, help Harish by writing a program for the same in C++.

Solution: The code to resolve this issue using the std::to_string() function is as follows:

Code:

#include <iostream>
#include <string>

int main() {
    float num1 = 3.14159;
    float num2 = 2.71828;
    float sum = num1 + num2;
    
    std::string result = std::to_string(sum);
    //using the to_string inbuilt function

    std::cout << "The sum of the numbers is: " << result << std::endl;
    //printing the output to the console
    
    return 0;
}

Output:

The sum of the numbers is: 5.85987

Code Explanation:

  • The software adds up two floating-point numbers, num1 and num2, in order to find their total.
  • The resultant sum value is converted to a string using the std::to_string() method.
  • Std::cout is used to output the resultant string.

Sample Problem-4: Using Approach-4

Problem Definition: Priyanka wants to write a program that reads in a floating-point number from the user and outputs it as a string with exactly 5 decimal places for maintaining a record. Help Priyanka to write the program for the same in C++.

Solution: The code to resolve this issue using the stringstream method is as follows:

Code:

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

int main() {
    float num;
    std::cout << "Enter a floating-point number and press Enter: ";
    std::cin >> num;
    std::stringstream ss;
    //creating the object of stringstream
    ss << std::fixed << std::setprecision(5) << num;
    //setting precision to 5

    std::cout << "The string representation of the number is: " ;
    std::cout<< ss.str() << std::endl;
    //printing the output to the console

    return 0;
}

Output:

Enter a floating-point number and press Enter: 3.1415926535
The string representation of the number is: 3.14159

Code Explanation:

  • The user is prompted to enter a floating-point number, which is then read in using std::cin.
  • It declares a stringstream object with the name ss.
  • Using the std::fixed and std::setprecision() functions, the num value is inserted into the stringstream object with a fixed precision of 5 decimal places using the operator.
  • The str() function is used to extract the resultant string from the stringstream object, and std::cout is used to print the string.

Conclusion

A float can be converted to a string in C++ using a variety of methods. The fastest and most practical method for doing this in C++ is the std::to_string() function.

It is a common library function that is simple to use and does not require a separate buffer. Moreover, it offers automatic rounding and does not require the decimal places to be specified.

Other methods, such as sprintf() or stringstream, may be more suitable for formatting or manipulating strings in a more complex way.