- Compiler: GCC 4.7.2 (Debian 4.7.2-5)
- Platform: Linux 3.2.0 x86 (Debian 7.1)
I am attempting to write my own character string to float conversion function. It is basically a cheap ripoff of strtof(), but I can't get it to mimic strtof() exactly. I do not expect my function to mimic strtof() exactly, but I want to know why it differs where it does. I have tested a couple different strings and I found that the following strings have different values when the are given to my function and when given to strtof() and when they are printed using printf("%.38f")).
- 1234.5678
- 44444.44444
- 333.333
- 777.777
Why does this happen? (Also feel free to point out any other mistakes, or inform me of any other strings that also have different values (there is no way I can find them all).)
#include <stdlib.h>
#include <stdio.h>
#include <float.h>
#include <math.h>
int dec_to_f(char *dec, float *f)
{
int i = 0;
float tmp_f = 0;
if(dec == NULL) return 1;
if(f == NULL) return 2;
if(dec[i] == '\000') return 3;
if(dec[i] == '-')
{
i++;
if(dec[i] == '\000') return 3;
for(; dec[i] != '\000'; i++)
{
if(dec[i] == '.')
{
float dec_place = 10;
int power_of_ten = 1;
for(i++; dec[i] != '\000'; i++, power_of_ten++, dec_place *= 10)
{
if(dec[i] >= '0' && dec[i] <= '9')
{
if(power_of_ten > FLT_MAX_10_EXP) return 4;
else tmp_f -= (dec[i] - '0') / dec_place;
}
else return 5;
}
break;
}
if(dec[i] >= '0' && dec[i] <= '9')
{
tmp_f = tmp_f * 10 - (dec[i] - '0');
if(!isfinite(tmp_f)) return 6;
}
else return 5;
}
}
else
{
if(dec[i] == '+')
{
if(dec[i+1] == '\000') return 3;
else i++;
}
for(; dec[i] != '\000'; i++)
{
if(dec[i] == '.')
{
float dec_place = 10;
int power_of_ten = 1;
for(i++; dec[i] != '\000'; i++, power_of_ten++, dec_place *= 10)
{
if(dec[i] >= '0' && dec[i] <= '9')
{
if(power_of_ten > FLT_MAX_10_EXP) return 7;
else tmp_f += (dec[i] - '0') / dec_place;
}
else return 5;
}
break;
}
if(dec[i] >= '0' && dec[i] <= '9')
{
tmp_f = tmp_f * 10 + (dec[i] - '0');
if(!isfinite(tmp_f)) return 8;
}
else return 5;
}
}
*f = tmp_f;
return 0;
}
int main()
{
printf("FLT_MIN = %.38f\n", FLT_MIN);
printf("FLT_MAX = %f\n", FLT_MAX);
float f = 0;
int return_value = 0;
char str[256];
printf("INPUT = ");
scanf("%s", str);
return_value = dec_to_f(str, &f);
printf("return_value = %i\nstr = \"%s\"\nf = %.38f\nstrtof = %.38f\n", return_value, str, f, strtof(str, NULL));
}