Search code examples
cxc8

sprintf() does not align right


I'm using MPLAB 5.25 with XC8 (2.10) to compile a program for a PIC18F42K47.

I want to print right aligned to a buffer, but the output is always aligned left. Here is my Code:

uint8_t Str_1[10] = {0};
uint8_t Str_2[10] = {0};
uint8_t Str_3[10] = {0};

sprintf(Str_1, "%3.2f", 12.345);    // -> "12.35" 
sprintf(Str_2, "%04.2f", 2.345);    // -> "2.35"  
sprintf(Str_3, "% 3.1f", -123.4);   // -> "-123.4"

Solution

  • The format specifier has a width argument left of the decimal point. This number describes the minimal total number of characters, not the number of characters before the decimal point.

    sprintf(Str_1, "%8.3f", 12.345);    // -> "  12.345"