Printing a 1 or 2 digit number as a 3 digit number

I have a variable being assigned in the loop and it could be a 1 digit, 2 digit, or 3 digit number.
How can I print it so that it's always a 3 digit number?

For instance,
if the variable is 7, I need it to print out as 007
if the variable is 32, I need it to print out as 032

Look at sprintf()
or
Write a function that examines the variable if it is <10 print two 0s then the number
else if < 99 print one 0 then the number

.

Use sprintf(), e.g.

 char buffer [50];
  int n, a=3;
  n=sprintf (buffer, "%03d",a);
  Serial.println(buffer);

I will try that. Thank you both.

An alternative is:

void setup() {
  Serial.begin(9600);
  char buffer [50];
  int n, a=4;
//  n=sprintf (buffer, "%03d",a);
  n = Pad(buffer, a);
  Serial.println(buffer);
}

int Pad(char *str, int val)
{
  char temp[4];
  int len;
  itoa(val, temp, 10);
  len = strlen(temp);
  switch (len) {
    case 1:
      strcpy(str, "00");
      strcat(str, temp);
      break;
    case 2:
      strcpy(str, "0");
      strcat(str, temp);
      break;
    case 3:
      strcpy(str, temp);
      break;
    default:
      len = -1;
  }
  return len;
}
   
    


void loop() {
  // put your main code here, to run repeatedly:

}

The sprintf() version uses 3034 bytes while the other version uses 2130 bytes. If you don't need all of the power found in sprintf(), the alternative can save you some memory.