4

How to format an integer as 3 digit string? If I give 3 formated string should be 003

printf("%03d\n", 3); // output: 003 

This doesn't work in Arduino.

  • You can use sprintf with a char array buffer and then pass it to Serial.print(). – jfpoilpret Feb 21 '17 at 16:51
  • Thanks its worked, 'char buff[3]; sprintf (buff,"%03d",3); Serial.print(buff);' – user119o Feb 21 '17 at 17:07
  • 6
    Rather use char buff[4] as you need one byte for the terminating zero that will be added by sprintf. If you don't, it may overwrite some value in your stack, leading to hard to understand problems. – jfpoilpret Feb 21 '17 at 17:12
  • Or you could setup printf() to print through Serial. This way you don't have to allocate room for sprintf(), which can be (as you just experienced) error prone. – Edgar Bonet Feb 21 '17 at 18:10
  • 1
    BTW, you will need more than 4 chars if the number you print happens to be less than -99 or more than 999. With buffer[7] you can safely print any int, and with buffer[12] you can print any long. – Edgar Bonet Feb 21 '17 at 20:53
2

The standard C function printf print to stdout. Arduino doesn't has a stdout. You can print to Serial, but must prepare/format the string first.

Instead of printf, use snprintf. It prints to a char array, which you later can use with Serial.print, or whatever other function that take a string.

void setup() {
  Serial.begin(9600);
  while(!Serial);

  char buffer[4];
  snprintf(buffer,sizeof(buffer), "%03d", 3);
  Serial.println(buffer);
}

void loop() {

}

Note: all the comments apply to this answers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.