Displaying floats aligned right on LCD

Frustrating that a task so simple is so difficult.
After an evening of googleing, I see I'm not alone with this. :o

There must be a simple solution to this simple task. I have a float that goes from zero to 30000. I want to display it on my 16x2 LCD as follows: Under 1000 it shows the number as is. Over 1000 it shows 12323 = 12.3k for example.

That's easy.

But the problem is in the simple part, how do I add empty chars (spaces) in front of the numbers, if it happens to be a short number like 345 or 1.2k.

I don't want "0345" or "01.2k", I want " 345" or " 1.2k".

I need to check the length of the char array and add spaces if needed. How do I do that? Is that a completely stupid approach?

Here's a snippet where "val" is a float at 0-30000 range, "dispc" is char[7], flag is int, lcd is my display object using i2c.

    case 3: lcd.setCursor(4, 0); lcd.print(val);
      temppi = val;
      if (val > 999) {
        val = val / 1000;
        dtostrf(val, 2, 1, dispc);
        flag = 1;
      }
      else {
        dtostrf(val, 4, 0, dispc);
        flag = 0;
      }
      lcd.setCursor(4, 1); lcd.print(dispc); if (flag == 1)lcd.print("k");
      break;

something like this...

double myArray[] = {999.1, 1199.0};

void setup() 
{
  Serial.begin(9600);
  char lcdBuffer[17];
  for(auto a : myArray)
  {
    if(a < 1000)
    {
      sprintf(lcdBuffer, "something:%6d", int(a));
      Serial.println(lcdBuffer);
    }
    else
    {
      sprintf(lcdBuffer, "something:%3d.%dk", int(a) / 1000, (int(a) / 100) % 10);
      Serial.println(lcdBuffer);
    }
  }
}

void loop() {
  // put your main code here, to run repeatedly:

}

Outputs:

something:   999
something:  1.1k

Thank you!

Your code worked well and I also managed to understand it, which is the point here. :slight_smile:
I just realised that in some rare cases the value might go over 32k. With a little modification it now displays values up to 32M.
Modulo didn't seem to work with data type long, so I had to use int and go with val=val/100 etc.

    case 3:
      lcd.setCursor(4, 0); lcd.print(val); //raw value for debugging
      if (val > 999) {
        val = val / 100;
        sprintf(dispc, "%2d.%dk", int(val) / 10, int(val) % 10);
      }
      else sprintf(dispc, "%4df", int(val));
      lcd.setCursor(4, 1); lcd.print(dispc);
      break;