## Count the number of digits in a number using python :

Using python, count the number of digits in a number. Get the input from the user and print out the result. We will show you two different ways to calculate digits.

## Solution 1 :

1. Take the user input, create one variable to store the count

2. Using a while loop, each time change the number to number/10, i.e. if the number is 132 next time it will be 132/10 = 13

3. Increment the count by one and Repeat it till the number become 0.

4. Print the count.

count = 0 number = int(input("Enter a number ")) while (number > 0): number = number//10 count = count + 1 print ("Total number of digits : ",count)

### Example :

For 1234 :

Step :1: number = 1234 / count = 0 ,

Step :2: number 1234/10 = 123/count = 1,….

Step : 4 : number 1/count = 3,

Step :5: number 1/10 = 0 .On step 5, it will not enter the while loop and print the count as 3.

## Solution 2 :

Instead of using a while loop, we can directly convert the integer to a string and get the length of the string :

count = 0 number = int(input("Enter a number ")) print ("Total number of digits : ",len(str(abs(number))))

‘abs’ is used to get the absolute value of a number. i.e. to handle the case even if the number is negative.

### Example :

Enter a number 123 Total number of digits : 3 Enter a number -1234 Total number of digits : 4

**You might also like :**

- Find the number of cpu count using python
- Count the number of words in a file using python
- Count the total number of characters in a string using python
- Count the number of blank spaces in a file using python
- Python program to find LCM of two numbers
- Python program to sort words of a string in alphabetical order

## 3 Comments

## BWAMPjbZ3HM · June 29, 2018 at 6:50 am

381679 9215As I website possessor I believe the content material here is rattling great , appreciate it for your efforts. You should keep it up forever! Good Luck. 211293

## Grégory · December 23, 2018 at 10:08 pm

Hi,

Actually provided there are no leading zeroes and the number is a positive integer, the number of digits turns out to be exactly int(math.log10(i))

Cheers,

## admin · December 24, 2018 at 3:02 am

Thanks for the input, GRÉGORY….