How to get the length of integer numbers ?

Hello,

I am newbie with the Arduino, and my last c++ coding experiences were many years ago...

I am looking for a way to position correctly an integer number on my LCD display. I want to place them right-aligned on the display, so I need to know the length = number of characters of this value.
Example: I am looking for a function with the output of 3 for the input 100, a 4 for input -200, or a 2 for input 15.

My first approach was to convert the number (int type) into a string, and use the sizeof() command, but I found no appropriate type conversion.

Or is there any other feasible way for placing values correctly right-aligned on the LCD ?

regards,
Tütenflieger

You can use the itoa function to convert to a string, and then the strlen function to get the length of the string.

Or, a simple nested if test:

int someValue = 14156;
int valLen = 0;

if(someValue > 9999)
   valLen = 5;
else if(someValue > 999)
   valLen = 4;
else if(someValue > 99)
   valLen = 3;
else if(someValue > 9)
   valLen = 2;
else
   valLen = 1;

You'd need to make some changes if the number could be negative (test the absolute value and add 1 to the length).

If you're going to pad with spaces to right align, you might want to look at using sprintf with a %nd format specifier, replacing n with the maximum number of digits a value can have. That way, the padding would be done for you, and all strings would be the same (known) length.

You could try something like this:

// max. num. digits is 16 in this example...
int iNum = 314159;
char acBuf[16 + 2]; // added 1 for NULL termination and 1 for the minus sign
sprintf( acBuf, "%16d", iNum );

int iNum = 314159;
char acBuf[16 + 2]; // added 1 for NULL termination and 1 for the minus sign

On the Arduino, an "int" can't be longer than five digits (-32768...+32767), plus sign, so 16 digits is overkill.
Even with 32 bit "int"s, you've only got 10 digits plus sign to worry about.
Besides, this doesn't tell you how manty decimal digits the number has.
One way might be to take logs.