String(*float*, 0).length gives strange result

Hi,

I'm trying to print a couple of floats (some with, some without decimal digits) right aligned on an OLED. To do that I use .length() to find out where to put the cursor. For most numbers, my code works. for positive, single digit numbers, the result is weird:

      float pi = 3.1415;
      u8g2.print(String(pi, 2));           // gives "3.14" - as expected
      u8g2.print(String(pi, 2).length());  // gives "4" - as expected 

      u8g2.print(String(pi, 0));           // gives " 3" - note the leading blank
      u8g2.print(String(pi, 0).length());  // gives "2" as opposed to the expected "1" due to the leading blank
[hr]

Any idea why that is happening? - Or how to do it better?

Many thanks,
Frank

Hi Frank. No idea why that is happening.

Suggest you use dtostrf(). This will make things easier for you because it right-aligns. Also suggest you avoid using String class, especially on Uno & similar. Stick to using character arrays.

frankp:
Any idea why that is happening?

String::String(float value, unsigned char decimalPlaces)
{
  init();
  char buf[33];
  *this = dtostrf(value, (decimalPlaces + 2), decimalPlaces, buf);
}

It's the +2 that inserts a blank before the 3 of your pi.
That error occures on all values between 0 and 10 (exclusive) if there are no decimal places to be printed.

You could fix that with a .trim() if you insist on using String.

Better would be to use the correct parameters for dtostrf directly.