How to Zero Pad?

Hi. I'm in the process of building a speedo for my motorbike. It's pretty much done except for the fact i've no idea how to zero pad in Wiring.

Is there a function/operator available or does it involve some bodging?

Your using Wiring?

I thought the language in the Arduino IDE is wiring. That or some kind of C.

No it's based on Wiring. It's essentially C/C++ (using avr-gcc to compile).


What do you mean by zero the pad?

What I mean by zero pad is to format a number. Say I have a range of expected numbers, say 0 to 100, and I want every single one to be shown as a 3 digit number i.e. 1 = 001 In python it's easy

>>> a = 1
>>> "%03d" % a

Something like this ought to do it:

void setup(){ 
  Serial.print("Try to print 13 as 0013: ");
  padding( 13, 4 );

void loop(){/*nothing to loop*/}

void padding( int number, byte width ) {
  int currentMax = 10;
  for (byte i=1; i<width; i++){
    if (number < currentMax) {
    currentMax *= 10;

I think this should print:

Try to print 13 as 0013: 0013


But he did forget to put the opening curley bracket in the padding function) :wink:

Oh. Bummer.
Thank you mem![/edit]

Cheers. The code looks good from here even if it isn't a single line solution. Python + AVR would be awesome.

Just to show that you can have a one line solution on Arduino , if you include the following line in your sketch:

#define padding(number,width) for(int i=1; i < width - log10(number); i++) Serial.print(‘0’); Serial.println(number,DEC);

The following code :


This only works for numbers greater than 0 and its submitted with tongue planted firmly in cheek. My friend AlhpaBeta’s function is a more efficient and flexible. (But he did forget to put the opening curley bracket in the padding function) :wink: