在Python中,如何找到整数中的位数?


当前回答

这是另一种计算任何数字的小数点前的位数的方法

from math import fabs

len(format(fabs(100),".0f"))
Out[102]: 3

len(format(fabs(1e10),".0f"))
Out[165]: 11

len(format(fabs(1235.4576),".0f"))
Out[166]: 4

我做了一个简短的基准测试,进行了10,000次循环

num     len(str(num))     ----  len(format(fabs(num),".0f")) ---- speed-up
2**1e0  2.179400e-07 sec  ----     8.577000e-07 sec          ---- 0.2541
2**1e1  2.396900e-07 sec  ----     8.668800e-07 sec          ---- 0.2765
2**1e2  9.587700e-07 sec  ----     1.330370e-06 sec          ---- 0.7207
2**1e3  2.321700e-06 sec  ----     1.761305e-05 sec          ---- 0.1318

这是一个较慢但更简单的选择。

但是即使这个解也会给出错误的99999999999998

len(format(fabs(9999999999999998),".0f"))
Out[146]: 16
len(format(fabs(9999999999999999),".0f"))
Out[145]: 17

其他回答

如果你想要一个整数的长度等于这个整数的位数,你总是可以把它转换成字符串,比如str(133),然后像len(str(123))一样找到它的长度。

假设您要求的是可以存储在整数中的最大数字,则该值与实现有关。我建议你在使用python时不要这样想。在任何情况下,相当大的值都可以存储在python 'integer'中。记住,Python使用鸭子类型!

编辑: 我在澄清提问者想要数字数之前给出了我的答案。就此而言,我同意公认答案所建议的方法。没什么可补充的了!

计算w/o将整数转换为字符串的位数:

x=123
x=abs(x)
i = 0
while x >= 10**i:
    i +=1
# i is the number of digits

不需要转换为字符串

import math
digits = int(math.log10(n))+1

也可以处理0和负数

import math
if n > 0:
    digits = int(math.log10(n))+1
elif n == 0:
    digits = 1
else:
    digits = int(math.log10(-n))+2 # +1 if you don't count the '-' 

你可能想把它放在一个函数中:)

以下是一些基准测试。len(str())对于非常小的数字已经落后了

timeit math.log10(2**8)
1000000 loops, best of 3: 746 ns per loop
timeit len(str(2**8))
1000000 loops, best of 3: 1.1 µs per loop

timeit math.log10(2**100)
1000000 loops, best of 3: 775 ns per loop
 timeit len(str(2**100))
100000 loops, best of 3: 3.2 µs per loop

timeit math.log10(2**10000)
1000000 loops, best of 3: 844 ns per loop
timeit len(str(2**10000))
100 loops, best of 3: 10.3 ms per loop
def count_digit(number):
  if number >= 10:
    count = 2
  else:
    count = 1
  while number//10 > 9:
    count += 1
    number = number//10
  return count