获取float(python)中某个数字的位置

时间:2018-01-03 18:02:45

标签: python floating-point

说我有一个浮动0.001000然后我想要输出4

更多例子:

0.1 -> 2
1 -> 1
0.00001000 -> 6

所有输入都是这样的(1和0) 你怎么能在python3.6中做到这一点?

或许有一种方法可以直接将浮点数截断为相同的数字? e.g

0.00100 
2.44521 
-------
2.445

3 个答案:

答案 0 :(得分:0)

my_float = 0.0001

转换为字符串

index = str(my_float).find('1')

诀窍在于占小数点。

if index == 0:
    output = 1
else:
    output = index

这仅在小数点前严格一位数时才有效。

<强>可替换地:

my_float的倒数。

my_float_inverse = 1/my_float

然后转换为字符串并获取长度。

output = len(str(my_float_inverse))

仅在my_float <= 1和上面指定的条件成立时才有效。

答案 1 :(得分:0)

漂浮物有时是残酷的。无论如何,如果你的浮点数总是小于或等于1,你可以使用这样一个片段

import math
f = 0.00001 # your float

int(math.log10(round(1/f)))+1

答案 2 :(得分:0)

请执行以下操作:

my_float = 0.001000

# Converts your float to a string without the '.'
my_str = str(my_float).replace('.', '')

# Get the index of the first '1' in the string
index_of_first_one = my_str.index('1') + 1

print(index_of_one)  # 4

此方法仅适用于1中的float