Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

zero-pad

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.

like image 595
Adam Siler Avatar asked Feb 16 '09 20:02

Adam Siler


People also ask

How do you count digits in integers?

The formula will be integer of (log10(number) + 1). For an example, if the number is 1245, then it is above 1000, and below 10000, so the log value will be in range 3 < log10(1245) < 4. Now taking the integer, it will be 3. Then add 1 with it to get number of digits.

How do you count the number of digits in a for loop?

First, we will calculate count the number of digits using for or while loop. Firstly, the number will be entered by the user. Suppose we declare the variable 'n' and stores the integer value in the 'n' variable. We will create a while loop that iterates until the value of 'n' is not equal to zero.

How do you count the number of digits in an integer in Python?

If you want the length of an integer as in the number of digits in the integer, you can always convert it to string like str(133) and find its length like len(str(123)) .


1 Answers

This should do it:

int length = (number ==0) ? 1 : (int)Math.log10(number) + 1; 
like image 133
Nicholas Mancuso Avatar answered Nov 03 '22 18:11

Nicholas Mancuso