atof() for float instead of double
Asked Answered
B

2

9

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.

Bilabiate answered 7/12, 2016 at 8:40 Comment(4)
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.Triadelphous
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.Elaterid
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.Zerlina
Consider rolling your own version, or checking if your platform offers platform-specific function for this taskEfrem
M
6

Use strtof instead, it will return a float.

See documentation here

Mothering answered 7/12, 2016 at 8:43 Comment(1)
Question is tagged [ansi-c]. According to this reference strtofwas 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)Taraxacum
A
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.

Ailey answered 7/12, 2016 at 13:57 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.