8

atof() returns a double, which results in a warning when I assign it to a float-value (and yes, I definitively have to use float).

So my question: is there a atof()-variant available which returns a plain float? Or do I have to solve this by a cast - which would be a pity because it wastes resources for creating a double which will be thrown away immediately.

Mathieu
  • 8,840
  • 7
  • 32
  • 45
Elmi
  • 5,899
  • 15
  • 72
  • 143
  • 3
    It really doesn't matter. If you assign the result to a variable it doesn't matter if you cast it or not, no more memory will be used and the compiler might have some nice optimized function that will make it all negligible. Don't do premature optimizations, concentrate on writing good and readable and maintainable code first of all. – Some programmer dude Dec 07 '16 at 08:44
  • 2
    Unless you're on an embedded platform with software floating point, your CPU most likely stores all floating point values in registers that are double sized. – Art Dec 07 '16 at 09:13
  • 1
    For the record, I'm looking at this question because I am on an embedded platform with hardware single precision and software double precision float. – ojs Aug 23 '17 at 16:38
  • Consider rolling your own version, or checking if your platform offers platform-specific function for this task – M.M Oct 01 '17 at 09:40

2 Answers2

5

Use strtof instead, it will return a float.

See documentation here

Henningsson
  • 1,275
  • 1
  • 16
  • 23
  • 2
    Question is tagged [ansi-c]. According to [this reference](http://en.cppreference.com/w/c/string/byte/strtof) `strtof`was added in C99, so you're at compilers mercy on whether that function exists. (BTW www.cplusplus.com is a poor reference for C questions) – user694733 Dec 07 '16 at 08:51
0

If the platform does have a direct "string to float" conversion routine and the compiler is optimizing, it will certainly call that conversion routine via:

char *buf = ...
float y; 
if (sscanf(buf, "%f", &y) == 1) Success();

If not, then use

float y = (float)atof(buf);

Note that the second could be optimized by the compiler to call the "string to float" if it violates the subtle double rounding that otherwise occurs with this 2nd code.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256