Printf broken in Mbed 2?

I’m noticing that padding of right-justified printf output just does not work. I poked around the forum and find numerous complaints regarding later os versions and difficulty printing floats but nothing specific to os 2. Do I got this right? (or am I just fumbling my code ; ) If yes, is there a ready work-around available ? Tnx !!

Hello Gary,

Could you please show the format you use for padding?
The following code works fine in Mbed 2 on LPC1768:

#include "mbed.h"

Serial      pc(USBTX, USBRX, 115200);
DigitalOut  led1(LED1);

int main()
{
    while (1) {
        led1 = !led1;
        pc.printf("pi = %10.2f\r\n", 3.14);
        wait_ms(1000);
    }
}

Hi Zoltan,

Tnx for taking a look. When I run the following:

#include “mbed.h”

Serial pc(USBTX, USBRX, 115200);
DigitalOut led1(LED1);

int main()
{
pc.printf(“%2.2f\r\n”, 27.6);
pc.printf(“%2.2f\r\n”, 8.3);
}

Output is:
27.6
8.3

Would have expected:
27.6
8.3 (left padded w/ single space)

Am I just coding this incorrectly? Tnx !!

My understanding of the format parameter for printing floating point numbers, e.g. %2.2fis as follows:
The digits before the . char specify the minimum number of all digits to be printed. This includes also the digits to be printed after the decimal point!
If the actual number has more digits then all of them are printed.
If the actual number has less digits then the printed number is left padded with space(s).
The second digit in the format parameter specifies the maximum number of digits to be printed after the decimal point.

The number of spaces printed before the first digit can be calculated as:
number_of_spaces_printed_before_the_digits = total_number_of_digits_to_be_printed - actual_number_of_digits

For example in case of:

pc.printf("%2.2f\r\n", 8.3);
  • The minimum number of all digits to be printed is equal to 2. The actual number (=8.3) has 2 digits. Hence, the number of spaces to be printed before the digits is equal to 0 (no padding).
  • The maximum number of digits to be printed after the decimal point is equal to 2. The actual number (=8.3) has 1 digit after the decimal point (=3). Hence, the number of digits to be printed after the decimal point is equal to 1.

Tnx !! I’ve been playing w/ c++ for a couple of years now and thought I understood printf formatting. I didn’t ! I mistakenly thought that %3.2 formatted for 5 total digits, 3 before the decimal point. I got it now. Last query then. When I attempt to print a negative # the minus sign shifts my output 1 to the right. How can this be avoided? Tnx again Z !!

Think I’ve sorted the answer to that last question. In format %x.y, the x must include total number of digits + 1 for the decimal point and + 1 for the sign. Works a treat ! You have advanced my understanding Z so tnx again…