Mail Archives: djgpp/2001/04/18/14:45:11
Igor Bujna wrote:
> 
> Hi,
> i have this problem with atof();
> 
> char *buf = "-21.345\0";
> float f = 0;
> 
> f = atof ( buf );
> printf("%f",f);
> 
> , then i have this "-21.344999".
> What i must to do for it will be OK.
You don't have a problem with atof().  You have a problem with trying
to get 8 digits of significance from a type only guaranteed 6 digits of
significance:
#include <stdlib.h>
#include <stdio.h>
#include <float.h>
int main(void)
{
    const char *buf = "-21.345\0";
    float f = 0;
    double d = 0;
    f = atof(buf);
    printf("unadorned %%f applied to float: %f\n", f);
    printf("%%.3f applied to float: %.3f\n", f);
    printf("%%.*f (for FLT_DIG-2) applied to float: %.*f\n\n",
           FLT_DIG - 2, f);
    d = atof(buf);
    printf("unadorned %%f applied to double: %f\n", d);
    printf("%%.3f applied to double: %.3f\n", d);
    printf("%%.*f (for DBL_DIG-2) applied to double: %.*f\n\n",
           DBL_DIG - 2, d);
    return 0;
}
unadorned %f applied to float: -21.344999
%.3f applied to float: -21.345
%.*f (for FLT_DIG-2) applied to float: -21.3450
unadorned %f applied to double: -21.345000
%.3f applied to double: -21.345
%.*f (for DBL_DIG-2) applied to double: -21.3450000000000
- Raw text -