reverse engineered

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.

comments powered by Disqus