Skip to content

toFloat looses precision, respectively toDouble is missing #5985

Closed
@DIRR70

Description

@DIRR70

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() {
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions