How to add leading zeroes to a number in adafruit ssd1306 OLED

i want to have a number counter that has a number centered on the right side and zeroes all to the left of it until the number itself hits 5 digits, how can i do this?

The old sprintf() is still used for that. The format would be "%05d".
The full format is explained here:
Or you can get the length and then write zeroes in a for-loop.

[EDIT] Changed "%05s" to "%05d", oops, shame on me :woozy_face:

Centered on the right side of what ?
How many digits are you expecting ?

Alternative to @Koepel's suggestion you can;
Write all zero's to the display.
Set the cursor to where you want your count to be displayed then print the count.
Note the cursor will have to know the length of your count to be displayed to be sure to start writing at the correct position.

Unless you find this easier I would probably go with @Koepel's suggestion with a slight variation:
Test your variable / display count .....

if(count< 10000) append xx leading zero's
if(count< 1000) append x leading zero's
if(count< 100) append x leading zero's
if(count< 10) append x leading zero's

5 digits total

so would it be if(count< 1000) append ("0"), and so on and so forth? and do i need to add an int or define?

Simple method, useful for most types of displays:

if (count < 10000) display.print('0');
if (count < 1000) display.print('0');
if (count < 100) display.print('0');
if (count < 10) display.print('0');

SSD1306 can get complicated if you are not using a fixed-pitch font, because the amount of space needed for 5 digits will change depending on the specific digits used.

No, I think @david_2018 has converted this method into compliable code.

now depending on how many leading zero's you need you can add more like this:

if (count < 100000) display.print('0');
if (count < 1000000) display.print('0');
if (count < 10000000) display.print('0');

oh haha while waiting for a response i got creative and kinda brute forced it

 if(currentState == pressed) {
    display.setCursor(0, 0);
    ++ count ;
    if (count < 1) {
    if (count < 10) {
      display.setCursor(0, 0);
      display.setCursor(100, 0);
    if (count > 9){
      display.setCursor(0, 0);
      display.setCursor(75, 0);
    if (count > 99) {
      display.setCursor(0, 0);
      display.setCursor(50, 0);
    if (count > 999) {
      display.setCursor(0, 0);
    if (count > 9999) {
      display.setCursor(0, 0);
  while(digitalRead(BUTTON_PIN) == pressed) {
    display.println( count);

"d" rather than "s" I would think. @reesedoesgaming17 would be printing an int. For a long int, "ld".

O, I should not make such mistakes. I changed it.

1 Like

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.