Displaying FLOAT variables in Arduino
Displaying FLOAT variables in Arduino
It seems that the Arduino software doesn't have much support for displaying float variables, certainly the sprintf() function doesn't work.
However there is a useful c function called dtostrf() which will convert a float to a char array so it can then be printed easily
The format is
dtostrf(floatvar, StringLengthIncDecimalPoint, numVarsAfterDecimal, charbuf);
where
floatvar | float variable |
StringLengthIncDecimalPoint | This is the length of the string that will be created |
numVarsAfterDecimal | The number of digits after the deimal point to print |
charbuf | the array to store the results |
An example will serve to illustrate the behaviour
static float f_val = 123.6794; static char outstr[15]; void setup() { dtostrf(f_val,7, 3, outstr); Serial.begin(9600); Serial.println(outstr); } void loop(){ }
The output of this sketch is
123.679
which is 7 characters long, with 3 characters after the decimal point.
So what if f_val had the value 1.6794, what would be the output then? Well, it would still be 7 characters long, with 3 characters after the decimal point, but it would be padded at the beginning with spaces. I.e.
1.679
Get the idea?