Convert a string to float

Experts is there a function out there that will convert a string with an exponential component into a float?

1.902922E+01 -- i need to extract this from a file and store at as a float variable...

I am struggling to find someway of doing this - note that the format of the string is always the same - 6 numbers after the decimal point, then the E, then power term..
Who is Participating?
jkrConnect With a Mentor Commented:
Basically, there's the C and the C++ way to do that - e.g.
// C++ way using streams
#include <sstream>
#include <string>
using namespace std;
float str2float(const string& str) {
  stringstream ss;
  ss << str;
  float f;
  ss >> f;
  return f;
// C way using stdio
#include <stdio.h>
float str2float(const char* str) {
  float f;
  sscanf(str,"%e",&f); // %e for scientific format
  return f;

Open in new window

Ooops, and there of course also is '_ecvt()' and friends (see, e.g.
#include <stdlib.h>
#include <stdio.h>
int main( void )
   int     decimal,   sign;
   char    *buffer;
   int     precision = 10;
   double  source = 3.1415926535;
   buffer = _ecvt( source, precision, &decimal, &sign ); // C4996
   printf( "source: %2.10f   buffer: '%s'  decimal: %d  sign: %d\n",
           source, buffer, decimal, sign );

Open in new window

imladrisConnect With a Mentor Commented:
Or you could use atof. It's one of a family of functions that converts strings to numbers. The signature for atof is:

double atof(const char *);

and you can assign that to a float, of course.

float fr=atof("1.902922E+01");

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.