printfavr-gcc

Can snprintf format '-0'?


On AVR 8-bit, avoiding floats, I'm dividing a signed integer and formatting it with snprintf:

int16_t tempx10 = -5;
div_t temp = div(tempx10, 10);
char buf[10];
snprintf(buf, sizeof (buf), "%4d.%d°", temp.quot, abs(temp.rem));

This however produces 0.5 instead of -0.5.

What would be an elegant way to solve this?


Solution

  • The code that you provided omitted the negative sign when temp.quot was zero because div() returns a zero quotient for -5/10, and the format string didn't account for the original value's sign. You can add the sign manually and you can use abs(temp.quot) to prevent the quotient from repeating its sign. You can do it this way.

    #include <stdio.h>
    #include <stdint.h>
    #include <stdlib.h>
    
    int main() {
        int16_t tempx10 = -5;
        div_t temp = div(tempx10, 10);
        char buf[10];
    
        snprintf(buf, sizeof(buf), "%c%d.%d°",
                 (tempx10 < 0) ? '-' : ' ',
                 abs(temp.quot),    
                 abs(temp.rem));
    
        printf("Result: %s\n", buf);  
        return 0;
    }
    

    Output:

    Result: -0.5°