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


当前回答

coin_digit = str(coin_fark).split(".")[1]
coin_digit_len = len(coin_digit)
print(coin_digit_len)

其他回答

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

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

n = 3566002020360505
count = 0
while(n>0):
  count += 1
  n = n //10
print(f"The number of digits in the number are: {count}")

output: number中的位数为:16

对于子孙后代来说,这无疑是迄今为止解决这个问题最慢的方法:

def num_digits(num, number_of_calls=1):
    "Returns the number of digits of an integer num."
    if num == 0 or num == -1:
        return 1 if number_of_calls == 1 else 0
    else:
        return 1 + num_digits(num/10, number_of_calls+1)

所有的数学。Log10的解会给你带来问题。

数学。Log10速度很快,但当你的数字大于999999999999997时就会出现问题。这是因为浮点数有太多的.9,导致结果四舍五入。

因此,为了获得最佳性能,对于较小的数字使用math.log,并且只使用超出math.log处理范围的len(str()):

def getIntegerPlaces(theNumber):
    if theNumber <= 999999999999997:
        return int(math.log10(theNumber)) + 1
    else:
        return len(str(theNumber))

对于整数,可以使用以下方法快速完成:

len(str(abs(1234567890)))

获取"1234567890"的绝对值的字符串长度。

abs返回没有任何负号的数字(只有数字的大小),str将其转换为字符串,len返回该字符串的字符串长度。

如果你想让它为浮点数工作,你可以使用以下任何一个:

# Ignore all after decimal place
len(str(abs(0.1234567890)).split(".")[0])

# Ignore just the decimal place
len(str(abs(0.1234567890)))-1

供以后参考。