Im trying to print an integer from right to left on a 8x1 LCD display. So for example, if i print 100, the last 0 should be printed in column 7, the next 0 in column 6 and 1 in column 5.
I tried lcd.rightToLeft(); but it turns the digits around. I can set the cursor to start in column 7 but then 001 is printed out.
I thought maybe i could count each digit in the integer and move the setcursor column accordingly, but could not find a way of doing this with integers.
Any ideas?
think like this, you might need to tweak it a bit
char buffer[10];
int x = 100; // number to print
sprintf(buffer, "%d" x); //
len = strlen(buffer);
lcd.gotoxy(8-len, 0);
lcd.print(buffer);
Thanks Rob, just tried out the counting for now and printing to serial, works fine! Thank you
Attached a screenshot of the serial monitor

you can also do same trick to Serial
for (int i=0; i< 100; i++)
{
char buffer[10];
char spaces[] = " "; // 8 spaces
int x = random(50000); // random number to print
sprintf(buffer, "%d" x); //
len = strlen(buffer);
Serial.print(&spaces[len]);
Serial.println(buffer)
}
all the 100 numbers should be right aligned.
For serial, that sure seems like the hardway of doing field widths and justification, especially since xxprintf() routines like sprintf() were designed to do it for you.
Why use a simple "%d" format, a buffer with spaces in it, and then have to calculate offsets and columns based on the output string, when sprintf() will do all that for you?
The default justification for "%d" is is right adjusted & padded with spaces which appears to be what was wanted.
i.e.
sprintf(buffer, "%8d", x); //8 characters, right adjusted, <space> padded
For the LCD, I'd be concerned that the example code breaks down when the numbers transition between the total number of digits.
i.e. when you print 100 and then print 15 the display will show 115 instead of 15.
The LCD line has to either be cleared prior to printing the number or the buffer needs to be a fixed width and filled with spaces.
sprintf() with a field width can do the space buffer fill and right adjust as shown above.
--- bill
I suspect the the OP is only printing "small" numbers.
The sprintf() method is very useful. Remember that %u will print an unsigned integer. And %ld will print a signed long integer.
You can also pad with leading zeros instead of spaces if you want.
Just read the documentation for the standard C printf() function. Note that you need to #include <stdio.h> for the Compiler to "know" about printf.
David.