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?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
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

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");

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Editors IDEs

From novice to tech pro — start learning today.