Issues with converting float to string with sprintf

I see it too, so puzzling. Will investigate and post back with any findings and a schedule for a fix.

2 Likes

Iā€™m doing local builds with 0.4.4 and the following is yielding ā€œā€

char logmsg[256];
sprintf(logmsg,"%.2f", 3.26f);

was there a regression or did I misread the above comments?

There must be a regression. I get the same behavior.

Iā€™ll be sure to add a unit test to our CI build for this so it doesnā€™t slip by again.

Iā€™m sorry this managed to work itā€™s way out of the 0.4.4 release. Iā€™ve definitely fixed this and added an automated test so this shouldnā€™t happen again. The issue is here - https://github.com/spark/firmware/issues/576

The fix is in develop now, and will be rolled out with 0.4.5 Wednesday next week (2 Sept.)

3 Likes

For anyone looking for a workaround, you can replace

float value = 1.0;
sprintf(buf, "it's %f", value);
```

with

```
float value = 1.0
sprintf(buf, "it's %s", String(value).c_str());
```

(change `%f` to `%s` and explicitly convert the float to a string before passing to `sprintf`)

Thanks @mdma. From a memory perspective would that method be preferable to using sprintf?

Not really preferable, but doesnā€™t do any harm. On the photon memory fragmentation is less of an issue due to the relatively large heap. Just consider it a workaround until the 0.4.5 release.

Cheers :smile:

Another alternative, not very pretty though :smile:

float temp = dht.getTempCelcius();
int temp1 = (temp - (int)temp) * 100;
sprintf("%0d.%d", (int)temp, temp1);

@mdma - I tried your workaround and it worked fine with the small number in your example. I tried a larger number and it gave a value I wasnā€™t expecting :

float myfloat=340000.0;
sprintf(spark_var2, "%s", String(myfloat).c_str());

returns :

4294965149.4294483648

Ah yeah - thereā€™s an overflow issue. You can avoid that by reducing the number of digits of precision required.

float myfloat=340000.0;
sprintf(spark_var2, "%s", String(myfloat, 2).c_str());

This issue https://github.com/spark/firmware/issues/563 addresses that - fix is in develop and will be released with 0.4.5.

4 Likes

sprintf is working well with floats using the develop branch. Thanks!

1 Like

@mdma - any news on rolling out 0.4.5 to the cloud compiler ?

We are trying to get it out today!

9 Likes

You just made my weekend.

Jason

1 Like

Was it released ? I cant find an announcement.

Yup, itā€™s the new default in the web ide :wink:

1 Like

It Works!!! :slight_smile: :smile:
Thank you!

1 Like

Works great - thanks @mdma