0

How to find the length of integer? Like if I have variable A as below:

A = 1000;

Then it should return 4 as the length of that integer.

martineau
  • 119,623
  • 25
  • 170
  • 301
Vishal Barvaliya
  • 197
  • 1
  • 3
  • 14
  • 1
    There shouldn't contain semicolon, isn't it? – jizhihaoSAMA Nov 21 '20 at 15:58
  • 1
    Why do you ask and self answer a question that has already been asked so many times and has so many answers on SO?? – Thierry Lathuille Nov 21 '20 at 16:13
  • 1
    Integers don't have a length, despite that the old duplicate question entertained the idea. Numbers are not the same thing as their *textual representation*. It is an important and key skill for programmers to distinguish things in themselves from their representations. – Karl Knechtel Nov 21 '20 at 16:13
  • @ThierryLathuille self-answering questions is permitted and historically encouraged as a way to share knowledge. However, in this case it doesn't accomplish anything. – Karl Knechtel Nov 21 '20 at 16:14
  • @KarlKnechtelThat was my point. About your other comment, I totally agree - and the sad thing is that I found the duplicate by googling "number of digits of an int". – Thierry Lathuille Nov 21 '20 at 16:16

2 Answers2

2

you can do yhis thing by **converting Integer into String ** and you can easily find length of String very easily in python by using len() function;

A = 10000;
length = len(str(A));
martineau
  • 119,623
  • 25
  • 170
  • 301
Vishal Barvaliya
  • 197
  • 1
  • 3
  • 14
0

Mathematically it can be done with log10() and proper rounding, but easier with recursion

def num2length(x, len=0):
    if x < 10:
        return len+1
    return num2length(x/10, len+1)
    
print(num2length(1000))
pmod
  • 10,450
  • 1
  • 37
  • 50