0

How can I convert an integer to a string in C and include a leading zero if the integer has only one digit? The result is needed to print to an LCD Display and not to print to console.

#include <stdio.h>
#include <stdlib.h>

int main ()
{
    int i = 7;
    char buffer[10];
    itoa(buffer, i, 10);
    printf ("decimal: %s\n",buffer);
    return 0;
}

This code would print 7 but i need it to be 07. But numbers greater than 10 eg.: 77 should remain the same.

Daniel
  • 398
  • 2
  • 16

1 Answers1

3

Instead of itoa, you can use the sprintf function with a format specifier of %02d to force the inclusion of a leading zero:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i = 7;
    char buffer[10];
//  itoa(buffer, i, 10);
    sprintf(buffer, "%02d", i);
    printf("decimal: %s\n", buffer);
    return 0;
}
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83