For many of the Arduino processors, floats are disabled in sprintf.
Another way is to convert the float number to a string with the dtostrf() function then use the %s placeholder to put it into your snprintf() function. Note that snprintf() is safer to use.
float floatNumber = 3.141592;
void setup()
{
Serial.begin(115200);
char buffer[30]; // final string
char floatStr[10]; // float converted to string
dtostrf(floatNumber, 8, 6, floatStr); // 8 char min total width, 6 after decimal
snprintf(buffer, sizeof(buffer), "the float number is %s", floatStr);
Serial.println(buffer);
}
void loop()
{
}
Another version found in net and then moderated. Good as an exercise as the solution contains so many fundamental concepts of C Programming.
float n = 6.38;
char myData[10] = {0};
void setup()
{
Serial.begin(9600);
//--extract integer part------------
int iPart = (int)n; // ipart = 6
//--extract fractional part---------
float fPart = n - (float)iPart; //0.38
//-convert iPart into string and save in myData[]-------
int index = intToStr(iPart, myData);//
//-------place point at place marked by index-----------
myData[index] = '.'; //place point
//---- convert fPart to 3.8)----------
fPart = fPart * 10.0;//fPart = 3.80;
//-----extract 3 from 3.8----------------
int iPartF = (int)fPart; //iPrtF = 3
//--cnvert iPartF into string and append at end og myData-----
intToStr(iPartF, myData + index + 1); //
Serial.print(myData);
}
void loop()
{
}
int intToStr(int x, char str[])
{
int i = 0;
do
{
str[i] = (x % 10) + '0';//saving ASCII codes for digits of iPart
x = x / 10;
i++;
}
while(x !=0);
reverse(str, i);
str[i] = '\0';
return i;
}
void reverse(char *str, int len)
{
int i = 0, j = len - 1, temp;
while (i < j)
{
temp = str[i];
str[i] = str[j];
str[j] = temp;
i++;
j--;
}
}
i don't believe there's an issue printing an arbitrary # of decimal digits using Serial.println (). the issue is getting around the loat limitation using sprintf()
it's always a good question to ask "why" (search for "ask why seven times" or "The 7 levels of why" (some variation with "the Five Why's.") for literature on the topic) - let's you challenge what you really have in mind.