Arduino Float to String
If you have ever tried to use sprintf() on an Arduino to convert from a float to a string, you will notice it doesn't work.
sprintf(buf,"%f", floatvar);
The above function will most likely return a "?" to your char buffer.
If you google around, you'll see various functions that people have written to overcome this, but all of them seem broken in one way or another. The alternative is to use dtostrf(), a standard avr-libc function. This provides a simple, tested function to convert from a float to a string.
To use this function, simply replace sprintf() with dtostrf(), along with the self explanatory parameters below.
dtostrf(floatVar, minStringWidthIncDecimalPoint, numVarsAfterDecimal, charBuf);
As the function name suggests, this will also work for the conversion of doubles to strings.
Categories: Arduino
Tags: Arduino, double, dtostrrf, float, sprintf, string
Comments: 14 Comments.
hello my name is jorge castellar, I live in Barranquilla Colombia,
thanks for your help dtostrf
regards
[...] Arduino Float to String - http://dereenigne.org http://dereenigne.org/electronics/arduino/arduino-float-to-...posted at [...]
Thank you very much about this information. I battled with that sprintf() function whole day and wondered why the hell it isnt working. But finally now my lcd shield shows temperature...
[...] la respuesta vino de los propios foros de Arduino, del foro viejo para ser [...]
hi,
actually there is a workaround to get your binary linked against the float-enabled versions of printf and scanf libraries. see this post for details: http://srejbi.info/posts/16_arduino-printf-scanf-floats
cheers,
srejbi
[...] la respuesta vino de los propios foros de Arduino, del foro viejo para ser [...]
An example would be most welcome.
thanks
butch
Very helpful! This solved the mysterious sprintf() problem I was observing on my arduino. Many thanks indeed!
Thanks Jon for the example.
What determines the value in
static char dtostrfbuffer[0];
I have tried 0,1,10,100 and they all seem to work just fine.
Hi Butch,
dtostrfbuffer is a char array containing the string representation of the floating point number, floatvar.
Jon
Why can the char dtostrfbuffer[0] be any size and still work????
Hi George,
No, dtostrfbuffer can't be any size. Take this example where there are now three buffers in memory. The size allocated to each buffer is now incorrect, causing dtostrfbuffer1 to be overwritten by dtostrfbuffer2. Arrays of size 0 are legal though.
Jon
okay maybe you can help me, do you know why if I write
line 1: dtostrf(float1,0,2,variable1);
line 2: dtostrf(float2,0,2,variable2);
line 3: dtostrf(float3,0,2,variable3);
variable2 becomes nothing. Some how line 3 deletes variable2 data.