String print LCD integer

Hi, I need some help with my Arduino.
I wanted to create a string with a length of 3 characters.
and wanted to print this string on the LCD display.
these 3 characters will be an integer that can range between 0 and 999.

int number = 123 // range between 0 and 999
string a = number;  // the string must always be 3 characters long.
lcd.print(a);

My problem is how do I define the string with only 3 characters of space? that is, even if the number only has 1 character I want the string to have 3. That is, when printing it would be ("clear","clear",3)

You could use dtostrf, but that doesn't work with Strings

may be you just want something like

int number = 123;
if (number < 100) lcd.print(" ");
if (number < 10) lcd.print(" ");
lcd.print(number);

in plain text: just add blanks if you need them.

Try running this:

    char myNumberToPrint[4] = ""; //has to have size of 4 to include '\0';

    for(int theNumber = 0;theNumber<15;theNumber++){
        snprintf(myNumberToPrint, sizeof(myNumberToPrint), "%d  ", theNumber);
        lcd.print(myNumberToPrint);
        delay(100);
    }

by using snprintf(), you can add two spaces after the %d and then these will be added if the strlength of the integer is too low. So if theNumber = 9, the lcd will print 9 with two spaces, but if theNumber = 123, the ldc will print 123 with no spaces.

This works because snprintf() will make sure that whatever "%d " is, it will only ever copy the first 3 characters to ensure the final char in myNumberToPrint is a '\0'

1 Like

Sorry i've just seen that you want it in the format of:
" 1", " 10", "231"
i.e. white spaces before the number.

In order to do that, use the code in my previous reply and change the snprintf() line from:
snprintf(myNumberToPrint, sizeof(myNumberToPrint), "%d ", theNumber);
to
snprintf(myNumberToPrint, sizeof(myNumberToPrint), "%3d", theNumber);
and you will get it in the format you like

1 Like

it will probably work but i have a problem if you can help me.
the value of the number comes from an integer. how do i convert this integer?

int number = 123;
char myNumberToPrint[4] = number;
int number = 123;
char myNumberToPrint[4] = "";

snprintf(myNumberToPrint, sizeof(myNumberToPrint), "%3d", number);
1 Like

sorry my distraction :slight_smile:

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