ArduinoTom:
When displaying numbers on an LCD, how do you deal with numbers that vary in length? For example, when displaying RPMs on an LCD, the correct RPMs can go from 4-digits (such as 1500) all the way down to 2-digits (such as 75). When the number gets smaller, I can't figure out how to fully replace the old number. So, for example, if it goes from 1245 to 90, the LCD shows 9045 (which is the 90 as intended, plus the 45 still displayed from the 1245). I'm using the standard LiquidCrystal.h library, and the code I'm using looks like this:
lcd.setCursor(9, 0);
lcd.print(RPM);
Well, you can do it the painful byte-by-byte method that most people here espouse, you can clear the display before each write (makes the display blink) or you can do it the right way....
Use sprintf to format your data. For example, if you expect 4 digits or less, do this:
char buffer [18]; // a few bytes larger than your LCD line
uint16_t rpm = 1234; // data read from instrument
sprintf (buffer, "RPM = %4u", rpm); // send data to the buffer
LCD.print (buffer); // display line on buffer
/*****
Note that the above code will keep the numbers aligned. For example,
0, 10, 200 and 1000 RPM respectively will print like this:
RPM = 0
RPM = 10
RPM = 200
RPM = 1000
If you want leading zeros, use "%04u" instead of "%4u" in the format
for sprintf (above). Then you will get this:
RPM = 0000
RPM = 0010
RPM = 0200
RPM = 1000
*****/
Note that if you try to do this with floating point like this:
sprintf (buffer, "RPM = %4.0f", rpm);
It won't print the number, instead it will print a question mark like this:
RPM = ?
This is because the floating point library support is not included in the Arduino package by default.
If you want to use sprintf and would like to enable and disable floating point support at will, I have the mod to implement this (it gives you an option in "preferences" to turn floating point on and off).
Hope this helps.
(edit to add): The "%u" format character is for unsigned ints. If you use regular ints (which are signed), use "%d" instead.