Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
7 years, 5 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????
1 Answer
7 years, 5 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); } }
Your code with
<<code>>
tags so that it's easier to read...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