Skip to content
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

Use sprintf to output floats in Print/dtostrf #7068

Merged
merged 2 commits into from
Feb 10, 2020

Conversation

earlephilhower
Copy link
Collaborator

Fixes #7043

Two slightly different custom routines were implemented by hand in
dtostrf (an AVR-lib non-ISO function) and Print. This resulted in
inconsistent output of float/double vars when rounding was needed.

Replace them all with a call to sprintf(), removing the duplicated, not
quite correct code.

Print(String(float)) and Print(float) now generate the same output.

Fixes esp8266#7043

Two slightly different custom routines were implemented by hand in
dtostrf (an AVR-lib non-ISO function) and Print.  This resulted in
inconsistent output of float/double vars when rounding was needed.

Replace them all with a call to sprintf(), removing the duplicated, not
quite correct code.

Print(String(float)) and Print(float) now generate the same output.
@earlephilhower
Copy link
Collaborator Author

The example code in the original bug (with an INF and NAN added for checks) now reports the same results no matter if it's Print(float) or Print(String(float)):

#include <Arduino.h>

void setup() {
  Serial.begin(115200);
  while (!Serial) yield(); 
  int a = 1014;
  float b = 1014.45;
  double c = 1014.5;

  Serial.println();
  Serial.println(a);
  
  Serial.println();
  Serial.println(b, 1);
  Serial.println(b, 2);
  Serial.println(String(b,1));

  Serial.println();
  Serial.println(c, 0);
  Serial.println(String(c ,0));

  float n = nanf("x");
  Serial.println(n);

  float u = 1/0.0;
  Serial.println(u);

}

void loop() {
}
1014

1014.5
1014.45
1014.5

1014
1014
nan
inf

@devyte devyte added this to the 2.7.0 milestone Feb 9, 2020
@earlephilhower earlephilhower merged commit 11ae243 into esp8266:master Feb 10, 2020
// make sure the string is terminated
*out = 0;
char fmt[32];
sprintf(fmt, "%%%d.%df", width, prec);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, crap. Thank you for reminding me about that! I had a niggle about it, but it's been maybe 2 years since the whole -u print_float stuff.

I'll open a new issue. The solution is not clear to me now.

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

Successfully merging this pull request may close these issues.

[BUG]: Rounding Values when Using String Type Cast
3 participants