python在小数点后找到第一个非零数字

时间:2011-11-04 14:45:45

标签: python string floating-point

简单问题,如何找到小数点后的第一个非零数字。我真正需要的是小数点和第一个非零数字之间的距离。

我知道我可以用几行来做,但我希望有一些pythonic,漂亮和干净的方法来解决这个问题。

到目前为止,我有这个

>>> t = [(123.0, 2), (12.3, 1), (1.23, 0), (0.1234, 0), (0.01234, -1), (0.000010101, -4)]
>>> dist = lambda x: str(float(x)).find('.') - 1
>>> [(x[1], dist(x[0])) for x in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, 0), (-4, 0)]

4 个答案:

答案 0 :(得分:6)

最简单的方法似乎是

x = 123.0
dist = int(math.log10(abs(x)))

我将列表t的每对中的第二个条目解释为您想要的结果,因此我选择int()将对数舍入为零:

>>> [(int(math.log10(abs(x))), y) for x, y in t]
[(2, 2), (1, 1), (0, 0), (0, 0), (-1, -1), (-4, -4)]

答案 1 :(得分:5)

关注小数点后的数字的一种方法是删除数字的整数部分,留在小数部分,使用类似x - int(x)的数字。

隔离了小数部分,你可以让python用%e演示文稿为你做计数(这也有助于处理舍入问题)。

>>> '%e' % 0.000125
'1.250000e-04'
>>> int(_.partition('-')[2]) - 1
3

答案 2 :(得分:1)

虽然技术上可以使用一行(不包括import语句),但我还添加了一些额外的东西以使其更完整。

from re import search

# Assuming number is already defined.
# Floats always have a decimal in its string representation.
if isinstance(float, number):
    # This gets the substring of zeros immediately following the decimal point
    # and returns the length of it.
    return len(search("\.(0*)", "5.00060030").group(1))
else:
    return -1
    # or you can use raise TypeError() if you wanna be more restrictive.

这可能对您没有任何顾虑,但我认为为了完整起见我会提及它,在某些地区,句号和逗号在数字时交换。例如1,000,000.00可能是1.000.000,00。不确定Python是否承认这一点,但由于它不代表具有数千个分隔符的任何数字,因此您可以将模式,(0*)用于其他区域。同样,对你来说可能并不重要,但可能对其他读者而言。

答案 3 :(得分:0)

ZerosCount = Ceil(-Log10(Abs(value) - Abs(Floor(value)))) - 1