zero-pad

How can I count the digits in an integer without a string cast?


I fear there's a simple and obvious answer to this question. I need to determine how many digits wide a count of items is, so that I can pad each item number with the minimum number of leading zeros required to maintain alignment. For example, I want no leading zeros if the total is < 10, 1 if it's between 10 and 99, etc.

One solution would be to cast the item count to a string and then count characters. Yuck! Is there a better way?

Edit: I would not have thought to use the common logarithm (I didn't know such a thing existed). So, not obvious - to me - but definitely simple.


Solution

  • This should do it:

    int length = (number ==0) ? 1 : (int)Math.log10(number) + 1;