English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, we will learn how to convert strings to floating-point numbers and vice versa with examples.
The simplest way to convert a string to a floating-point number is to use the followingC ++ 11Function:
std :: stof() - Convert string to float
std :: stod() - Convert string to double
std :: stold() - Convert string to long double.
These functions are defined in the string header file.
#include<iostream> #include<string> int main() { std::string str = "123.4567"; // Convert a string to a floating-point number float num_float = std::stof(str); // Convert string to double floating-point number double double num_double = std::stod(str); std::cout << "num_float = " << num_float << std::endl; std::cout << "num_double = " << num_double << std::endl; return 0; }
Output Result
num_float = 123.457 num_double = 123.457
We can use the std::atof() function to convert a char array to double.
#include<iostream> // atoi() needs cstdlib #include<cstdlib> int main() { // Declare and initialize a character array char str[] = ""123.4567"; double num_double = std::atof(str); std::cout << "num_double = " << num_double << std::endl; return 0; }
Output Result
num_double = 123.457
We can use C ++ 11 std::to_string() function converts float and double to strings. For older C ++Compiler, we can use the std::stringstream object.
#include<iostream> #include<string> int main() { float num_float = 123.4567F; double num_double = 123.4567; std::string str1 = std::to_string(num_float); std::string str2 = std::to_string(num_double); std::cout << "Float to String = " << str1 << std::endl; std::cout << "Double to String = " << str2 << std::endl; return 0; }
Output Result
Float to String = 123.456703 Double to String = 123.456700
#include<iostream> #include<string> #include<sstream> // Use stringstream int main() { float num_float = 123.4567F; double num_double = 123.4567; // Create a stringstream object std::stringstream ss1; std::stringstream ss2; // Assign the value of num_float to ss1 ss1 << num_float; // Assign the value of num_float to ss2 ss2 << num_double; //Use ss1and ss2Initialize two string variables //Then use the str() function to convert it to a string format std::string str1 = ss1.str(); std::string str2 = ss2.str(); std::cout << "Float to String = " << str1 << std::endl; std::cout << "Double to String = " << str2 << std::endl; return 0; }
Output Result
Float to String = 123.457 Double to String = 123.457
Related conversions: Convert C ++String to int Conversion.