Salva Savall Salva Savall - 5 months ago 24
C Question

C: strtof wrong conversion by a unit

I'm having problems with strtof conversions, some values it works well but another ones it returns +1 or -1 of the value. My program reads the value from a file but for simplicity I have tried putting directly the value to strtof and it has the same behavior.

My simple code:

#include <stdlib.h>

int main(int argc, char **argv)
printf("%f", strtof("17309217",NULL));

It returns


The same value that it gives if I convert "17309216" or "17309215".

I have been doing some more tests and it seems a "pattern", "17309214" works well but "17309213", "17309212" and "17309211" all return "17309212". After this "17309210" works well but "17309209", "17309208" and "17309207" return "17309208", and so on...

What is the explanation for this behaviour? Now I convert the string with other methods, I don't need a method to convert it. I only want to know why strtof is doing this, so I can decide where I can use it and where can't.

I have been reading some other questions asked related to wrong conversions but all are related to the decimal rounding, not an entire unit.

Thanks in advance,

Answer Source

You're converting to a 32-bit floating point which may not have the precision to handle that many digits.