Possible firmware bug

Using Photon, v2.1.0 (also 2.0.1), I need to record a floating point value, convert it into a string, and send it to a web service.
I found something strange (or, possibly, I misunderstood something?)

Lets say I have
float test=12.301234;

I try to print it to console to check it:
Serial.println(test,DEC); → 12.3012342453 (correct)
Serial.println(test); → 12.30 (rounded, but correct)

But, when converting it to a string:
str1=String(test,DEC); Serial.println(str1); → 12.0424759989 (wrong, how was this calculated?)
str2=String(test); Serial.println(str2); → 12.301234 (correct)

I would expect
str1=String(test,DEC); Serial.println(str1);
to return the same output, but they do not. Even worse, how did 12.301234 get converted to 12.0424759989?!?

Any suggestions?

The String class is unreliable and char arrays (c-strings) are more portable. For most instances of string formatting, snprintf() does the job well. You can find numerous examples on the forum where this has been pointed out.


In this string constructor, the helper function used is flawed, as I’ve discovered in this post.


In this println() method, the helper function used is similar.

It looks like you’re using 10 for DEC, which explains why you’re seeing the error, because that string constructor will produce incorrect results when you specify 10 or more decimal places.

My only suggestion at the time would be to use snprintf() until the helper function is fixed.

For example:

char buff[33];
snprintf(buff, sizeof(buff), "%1.10f", test);

In addition to what @nrobinson2000 said.
I don’t see a constructor that would fit your call.
There is one that takes an integer and a base or one that takes a floating point and a precision but none for floating point with base AFAICT.

Hence, even if the conversion would be calculated correctly, you’d rather get a probably undesired result as DEC (10) would be interpreted as precision and if you used HEX (16) even more so as you’d still get a decimal representation with 16 (uncertain) decimal places.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.