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.

Posted: March 5th, 2011
Categories: Arduino
Tags: , , , , ,
Comments: 4 Comments.
Comments
Comment from jorge castellar - 22 September 2011 at 01:28

hello my name is jorge castellar, I live in Barranquilla Colombia,
thanks for your help dtostrf

regards

Comment from skvr - 29 October 2011 at 18:55

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 [...]