I'd like your advice on the most efficient way to format a float into a char array. The end goal is to display the float value on an LCD display, see below a pic of my problem.
Basically I have a float variable in which is a temperature value. It can be positive, negative, have one or two digits in the integer part. I use the following code to format it but I am not happy with it because it leaves blanks after the "A:" part when the temperature is, say, 8.7C, compared to when it is "-10.6C" for instance. Instead I'd like the "A:" part to be right against the temperature value.
char buff[10]; //Allocate temporary buffer to store the string
float TempExternal = 8.72; //my temperature
dtostrf(TempExternal,5,1,buff); //format the float variable into a one-digit precision, 5 characters long string
sprintf(p, "A:%5sC",buff); //p is a pointer to the final string to be displayed on the LCD
Maybe finding out the length of the integer part of the float (+ the sign when negative) before calling the dtostrf() function? It sounds a bit clumsy though...
it now works as epxected although my solution might still be a bit more convoluted than required.
One thing that makes things a bit harder for myself perhaps is that I don't want to clear the whole LCD prior to rewriting it (afraid of flickering), instead I am concatenating a single 24x4 character string then write it to the LCD. So I don't place the LCD carret at some position then write a string, which means I need to insert some space paddings between the strings in order to keep every line at 24 characters length.
So here is the code now (I had to use an extra buff2 buffer):
char buff[10]; //Allocate temporary buffer to store the string
char buff2[20]; //Allocate temporary buffer to store the string
float TempExternal = 8.72; //my temperature
dtostrf(TempExternal,1,1,buff); //format the float variable into a one-digit precision, n characters long string
sprintf(buff2, "A:%sC",buff);
p += sprintf(p, "%12s",buff2); //p is a pointer to the final string to be displayed on the LCD. 12 is because I have 12 characters left on the LCD line to write this string and I need padding in front