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