Hello everybody,
Unfortunately I haven't found any good solution for printing float/double values when using sprintf(). Arduino doesn't support "%lf", nor "%f" yet, so we need to find a different method.
Some people divide the float in two parts and print them, some are using dtostrf(). I am usually using -not necessarily better- a different approach, that might be worth sharing.
The following approaches, that I am aware of:
Using Casting*(my part)*:
double f = 0.13454;
Serial.print("Original value: ");
Serial.println(f);
char str[50];
sprintf(str, "String value using cast: %s", String(f, 5).c_str());
Serial.println(str);
Using part Devision*1,2*:
double f = 0.13454;
Serial.print("Original value: ");
Serial.println(f);
char str[50];
sprintf(str, "String value using devision: %d.%02d", (int)f, (int)(f * 100) % 100);
Serial.println(str);
Using dtostrf()1**: **
double f = 0.13454;
Serial.print("Original value: ");
Serial.println(f);
char str[50];
strcpy(str, "String value using dtostrf: ");
dtostrf(f, 2, 2, &str[strlen(str)]);
Serial.println(str);
I found the casting approach to be the best one, as it requires the least amount of code and the precision can be set accordingly. Though it is really an ugly data type converter.
Actually literally every Data type can be printed with this solution. (bumpy but works ; ) )
Are there any other better ideas?
[1] How to sprintf a float with Arduino - Yet Another Arduino Blog