Skip to content

Instantly share code, notes, and snippets.

@mmansion
Created July 22, 2013 18:10
Show Gist options
  • Select an option

  • Save mmansion/6056124 to your computer and use it in GitHub Desktop.

Select an option

Save mmansion/6056124 to your computer and use it in GitHub Desktop.
Arduino, Pad Integers for Formatted Printing
/*
auth: mmasnion
desc: get zero-padded string for numbers under 50,000
*/
int testNumber = 70;
void setup() {
Serial.begin(9600);
}
void loop() {
String paddedNumber = getPadded(testNumber); //converts to char
Serial.println(paddedNumber);
delay(1000);
}
String getPadded(int num) {
char buff[6];
char padded[7];
//sprintf function will convert the long to a string
sprintf(buff, "%.5u", num); // buff will be "01238"
padded[0] = buff[0];
padded[1] = buff[1];
padded[2] = buff[2];
padded[3] = buff[3];
padded[4] = buff[4];
padded[5] = buff[5];
padded[6] = '\0'; // The terminating NULL
return String(padded);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment