Converting Float/Double to String
1. Using to_string() function
Using the std::to string() function in C++11, we can convert float and double data types to strings.
Syntax:
string variable_name = std::to_string(number);
Here parameter number can be of any data type like float/double.
Example:
C++
// C++ program to convert // float/double into string #include<bits/stdc++.h> using namespace std; int main() { // Initializing the numbers float number1 = 678.1234; double number2 = 678.1234; // Converting float to string string float_str = std::to_string(number1); // Converting double to string string double_str = std::to_string(number2); cout<< "Float to String = " << float_str << endl; cout<< "Double to String = " << double_str << endl; return 0; } |
Output
Float to String = 678.123413 Double to String = 678.123400
2. Using stringstream and str() function
In this approach, we create stringstream object with the help of std::stringstream in C++, and then this object is assigned a value. The value can be of any data type like float/double. Then this object is converted to a string using the str() function in C++.
Example:
C++
// C++ program to convert // float/double into string #include<bits/stdc++.h> using namespace std; int main() { // Initializing the numbers float number1 = 678.1234; double number2 = 678.1234; // creating stringstream objects std::stringstream ss1; std::stringstream ss2; // assigning values to // stringstream objects ss1 << number1; ss2 << number2; // Converting float to string string float_str = ss1.str(); // Converting double to string string double_str = ss2.str(); cout<< "Float to String = " << float_str << endl; cout<< "Double to String = " << double_str << endl; return 0; } |
Output
Float to String = 678.123 Double to String = 678.123
C++ String to Float/Double and Vice-Versa
In this article, we will learn how to convert String To Float/Double And Vice-Versa. In order to do conversion we will be using the following C++ functions:
- std::stof() – convert string to float
- std::stod() – convert string to double
- std::atof() – convert a char array to double
- std::to_string – convert any data type number to string
Contact Us