I want to parse floating-point numbers from scratch in C.
But I found there is an obviously error because of the storage of float/double in computers is not precise enough.
Here is my code for parsing, regardless of the conditions that involves negative sign:
void parseFloat(double *coe, int *exp){
char c = 0;
double digit = 10;
*coe = 0, *exp = 0;
int state = 0;
while((c = getchar_unlocked()) !='\n'){
if(c == '.'){
state = 1;
continue;
}
if(c == 'e'){
state = 2;
continue;
}
if(state == 0){
*coe = *coe * 10 + c - '0';
}else if(state == 1){
*coe += (c - '0') / digit;
digit *= 10;
}else if(state == 2){
*exp = *exp * 10 + c - '0';
}else{
*coe = 0, *exp = 0;
break;
}
}
return;
}
And it got the totally intolerable wrong result because of the addition of trivial mistakes made by each loop step in parsing process:
input -> output
5.699141892149156e76 -> 5.699141892149156341 76
9.205357638345294e18 -> 9.2053576383452959675 18
So is there any decent method for parsing floating-point numbers more precisely?
And how did the build-in library like scanf("%f", &fpn)
implement it?
Thanks a lot!