-2

Sample.c:

#include<stdio.h>
#include<stdlib.h>

main()
{
    char str[10] = "111.1";
    float f = (float)atof(str);
    printf ("\n (%s  ,  %f) \n",str,f);
}

Output of above code is : (111.1 , 111.099998)

Please suggest whether i am missing something. Thanks in advance.

nvoigt
  • 75,013
  • 26
  • 93
  • 142
AkhilT
  • 21
  • 1
    Try to use it with a `double`. I often had some random issues by using `float` – Guillaume Munsch Jul 13 '15 at 09:59
  • 2
    its because of typecasting from double(return type of `atof`) to float, resulting into closest possible float. – Dayal rai Jul 13 '15 at 10:03
  • 1
    by default atof returns in double datatype. – Ishmeet Jul 13 '15 at 10:12
  • Floats have less precision than doubles. – udit043 Jul 13 '15 at 10:18
  • Not related to the problem, but 1) you don't need to hardcode the size of an array if you're initializing it, so here `char str[] = "111.1";` would've been enough 2) implicit `int` return type for functions is pretty old C; whatever you're learning from, I suggest you use something newer. – user4520 Jul 13 '15 at 10:22

2 Answers2

2

Changing from float to double helps a bit, but doesn't "solve" the "problem." First, there is no problem, just a perception that there is one. As Dayal Rai said, 111.099998 is the closest you can get to 111.1 using a float. But even a double cannot represent 111.1, as you will find if you print its value using more decimal places. See the reference quoted by Sohil Omer.

FredK
  • 4,094
  • 1
  • 9
  • 11
0

Use this , as atof returns double , Reference Man Page of atof()

double f = atof(str);

For more info, Double vs Float in C

Community
  • 1
  • 1
Sohil Omer
  • 1,171
  • 7
  • 14