6 years, 9 months ago.

function atof() lost precision (wrong conversion)

Hello, i'm trying to work with number and string, when i read the string 50.6 the program read the string well but, when a convert it with atof() and pc.printf("%f", result) it prints 50.999998

Here's just a little part of my code:

char txt[100]; char *p; float test; FILE *m_fFilePath = fopen("/sd/valeurs.txt", "r"); if(m_fFilePath != NULL) { pc.printf("read open\n\r"); fgets(txt, 100, m_fFilePath); p = strtok (txt,",") ; setpoint.f = atof(p); p = strtok (NULL,",") ; test = atof(p);

pc.printf("%s\n\r",p); PRINT 50.6

pc.printf("%f\n\r",test); PRINT 50.999998 [...]

How it is possible to lose precision with atof????

Your code with <<code>> tags so that it's easier to read...

char txt[100];
char *p;
float test;
FILE *m_fFilePath = fopen("/sd/valeurs.txt", "r");
if(m_fFilePath != NULL) { 
  pc.printf("read open\n\r");
  fgets(txt, 100, m_fFilePath);
   p = strtok (txt,",") ;
   setpoint.f = atof(p);
   p = strtok (NULL,",") ;
   test = atof(p);
  pc.printf("%s\n\r",p); // PRINT 50.6
  pc.printf("%f\n\r",test); // PRINT 50.999998
posted by Andy A 07 Jul 2017

It would help to know exactly what the input string looks like. And printf the txt string after you read it, to be sure you have what you think you have.

posted by Graham S. 08 Jul 2017

1 Answer

6 years, 9 months ago.

The atof() returns double type. So, your code implicitly converted from double to float and you lost precision.

http://www.cplusplus.com/reference/cstdlib/atof/

I wrote simple code below, and worked fine.

#include "mbed.h"

int main() {
    char buf[20];
    
    sprintf(buf, "50.6");
    printf("value = %s\n", buf);
    double f = atof(buf);
    printf("value = %f\n", f);
    
    while(1) {
        wait(0.2);
    }
}

Accepted Answer

A float is no so inaccurate that 50.6 would becomes 50.999998. 50.6 becoming 50.599998 I would accept but not an error of almost 1%, floats are more accurate than that. There must be something else going on as well.

posted by Andy A 07 Jul 2017