Arduino has a small limitation in sprintf function that does not print correctly float numbers.
The following test sketch demonstrates the problem

void setup()
{
Serial.begin(115200);
}

void loop()
{
float f = 123.12F;
Serial.print("Original value: ");
Serial.println(f);

char str[50];
sprintf(str, "String value: %f", f);
Serial.println(str);

Serial.println();
delay(2000);
}

You can see from the screenshot below that the float is always formatted a question mark '?'.


Using integer trick


There is a little trick to correctly print the float value using sprintf.

sprintf(str, "String value: %d.%d", (int)f, (int)(f*100)%100);


This trick works well only with positive numbers and formats the float with two fixed decimals.



Using dtostrf function


A better solution is to use the dtostrf function. It it is more flexible and works well also with negative numbers.
These two lines of code will write a string into the buffer with strcpy function and the append the float value using the dtostrf function.

strcpy(str, "String value using dtostrf: ");
dtostrf(f, 2, 2, &str[strlen(str)]);



Post a Comment