Convert from string to float

I am trying to convert a variable from string to float. But I'm getting wrong values. Below is my code.

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

main(int argc,char *argv[])
{
    char endTime[4][26];
    time_t timere;
    struct tm *tm_infoe;
    float dlay[4][3];
    time(&timere);
    tm_infoe = localtime(&timere);
    strftime(endTime[1], 26, "%Y%m%d%H%M%S", tm_infoe);
    printf("Endtime %s\n", endTime[1]);
    dlay[1][1]=atol(endTime[1]);
    printf("Value from atol:%ld\n", atol(endTime[1]));
    dlay[1][1]=atof(endTime[1]);
    printf("Float value from atof:%f\n", dlay[1][1]);
    sscanf(endTime[1], "%f", &dlay[1][1]);
    printf("Float value from sscanf:%f\n", dlay[1][1]);
}

Both the functions atof and sscanf are giving wrong values. Below is the output. Can you please tell me where is the mistake?

Endtime 20151018221710
Value from atol:20151018221710
Float value from atof:20151017668608.000000
Float value from sscanf:20151017668608.000000

atol is giving correct value, but I need it in float format.

Upvotes: 0

Views: 128

Answers (1)

ameyCU
ameyCU

Reputation: 16607

You should use double here instead of float .While you use float many numbers can go slight change . Therefore , you get such value , not wrong though .

Here a simple example using double -

#include <stdio.h>
int main(void){
   char s[]="20151018221710";       // your string 
   double a;                        // declare a as double
   sscanf(s,"%lf",&a);              // use %lf specifier for double
   printf("%f",a);                  //print value of a 
   return 0;
}

Output -

20151018221710.000000

Demo here

Upvotes: 1

Related Questions