Converting String to Float/Double

1. Using std::stof() and std::stod() function

stof() function takes a string object as an input and returns the floating point number corresponding to that string as an output. On the other hand stod() takes a string as input and returns double data type as an output.

Syntax:

float variable_name = std::stof(string_name);
double variable_name = std::stod(string_name);

Example:

C++




// C++ program to convert
// string into float/double
#include<bits/stdc++.h>
using namespace std;
  
int main()
{
    // Initializing the string
    string str = "678.1234";
  
    // Converting string to float
    float str_float = std::stof(str);
  
    // Converting string to double
    double str_double = std::stod(str);
  
    cout<< "string as float = " << str_float << endl;
    cout<< "string as double = " << str_double << endl;
  
    return 0;
}


Output

string as float = 678.123
string as double = 678.123

2. Using std::atof() function

In C++ the character array can be converted to any numeric data type like float/double using the help of atof() function. This function takes a string as a parameter and returns float/double as output.

Syntax:

float variable_name = std::atof(string_name);
double variable_name = std::atof(string_name);

Example:

C++




// C++ program to convert
// float/double into string
#include<bits/stdc++.h>
using namespace std;
  
int main()
{
    // Initializing the char array
    char str[] = "678.1234";
  
    // Converting char array to float
    float str_float = std::atof(str);
  
    // Converting char array to double
    double str_double = std::atof(str);
  
    cout<< "char array as float = " << str_float << endl;
    cout<< "char array as double = " << str_double << endl;
  
    return 0;
}


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:

  1. std::stof() – convert string to float
  2. std::stod() – convert string to double
  3. std::atof() – convert a char array to double
  4. std::to_string – convert any data type number to string

Similar Reads

Converting String to Float/Double

1. Using std::stof() and std::stod() function...

Converting Float/Double to String

...

Contact Us