Skip to content

toFloat looses precision, respectively toDouble is missing #5985

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
6 tasks done
DIRR70 opened this issue Apr 14, 2019 · 1 comment · Fixed by #5986
Closed
6 tasks done

toFloat looses precision, respectively toDouble is missing #5985

DIRR70 opened this issue Apr 14, 2019 · 1 comment · Fixed by #5986

Comments

@DIRR70
Copy link

DIRR70 commented Apr 14, 2019

Basic Infos

  • This issue complies with the issue POLICY doc.
  • I have read the documentation at readthedocs and the issue is not addressed there.
  • I have tested that the issue is present in current master branch (aka latest git).
  • I have searched the issue tracker for a similar issue.
  • If there is a stack dump, I have decoded it.
  • I have filled out all fields below.

Platform

  • Hardware: [ESP-12]
  • Core Version: [2.5.0]
  • Development Env: [Arduino IDE]
  • Operating System: [Windows]

Settings in IDE

  • Module: [Nodemcu]
  • Flash Mode: [dio]
  • Flash Size: [4MB]
  • lwip Variant: [v1.4]
  • Reset Method: [nodemcu]
  • Flash Frequency: [40Mhz]
  • CPU Frequency: [80Mhz]
  • Upload Using: [SERIAL]
  • Upload Speed: [921600]

Problem Description

Parsing a string into a double (using toFloat which internally uses atof) lacks of precision. It is fine for 4 Byte float, but not for 8 Byte double. In either case toFloat needs to be extended or toDouble (like in Arduino AVR) needs to be introduced!
If someone had a workaround, I would be very grateful :)

#include <Arduino.h>

void setup() {
  Serial.begin (115200);
  Serial.println ();

  float f = 20.0 / 3.0;
  Serial.println (f, 8); // 6.66666651
  String fs = String (f, 8);
  Serial.println (fs); // 6.66666651
  f = fs.toFloat ();
  Serial.println (f, 8); // 6.66666651

  double d = 20.0 / 3.0;
  Serial.println (d, 16); // 6.6666666666666669
  String ds = String (d, 16);
  Serial.println (ds); // 6.6666666666666669
  d = ds.toFloat ();
  Serial.println (d, 16); // 6.6666665077209472 :(
}

void loop() {
}
@DIRR70
Copy link
Author

DIRR70 commented Apr 15, 2019

Thank you earlephilhower, that was more than fast :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant