1

Topic: Convert a float to a string

Sorry if this is simple, I am a real beginner here.

I am using an Arduino. I have a float T (a temperature from a DS18B20).

I want to display it in the form XX.X°C.

I am missing something simple, but I don't have much hair to pull out, please help me save what little I have left.

Thank you.

2 (edited by Guillaume 2020-03-31 15:39:13)

Re: Convert a float to a string

Welcome,

You can use function dtostrf to convert float to string, then function strcat to add the "°C" behind, or you can simply use function sprintf:

float val = 12.3456789;
char str[8]; // buffer to hold string "-XX.X°C\0"

dtostrf( val, 5, 1, str );
strcat( str, "°C" );

// or

sprintf( str, "%.1f°C", val );

The downside of sprintf is, it uses a lot (1 to 2kB IIRC) of program space.

And to avoid buffer overflow if temperature sensor gives an incorrect reading like 12345°C (IDK if it's even possible),  you must check if the temperature is in a range that can fit inside the buffer (so -99 to 999, less than 4 characters in front of the dot), or increase buffer size.

3 (edited by Robin 2020-04-01 08:42:44)

Re: Convert a float to a string

Guillaume,

THANK YOU. Sorry for shouting, but I am happy.

I had a problem with the design in the editor. Now that I have sorted that out, it works.

Thank you also for the warning about buffer overflow as -127.0 is measured if the probe becomes disconnected. I have trapped this and change the string to "ERROR"

Robin
big_smile

4 (edited by KissInno 2020-10-23 18:59:20)

Re: Convert a float to a string

Hi Robin

I have been dealing with "Read buffer overflow". No real idea, where it is sudenly coming from.

Can't you post an exemple please?

Up to now my past versions were running well and I cannot understand what I did wrong to make RemoteXY unhappy adding a new page where all looks really fine.

Thanks.

Kissinno