zzz*_*247 4 python floating-point
我有一个函数将浮点数作为输入,输出只是小数部分。例如,get_decimal(4.45)should return 0.45,我们应该只返回正数。
我做了以下代码:
def get_decimal(n):
try:
return float('0.'+(str(n).split('.',1))[1])
except:
return 0
Run Code Online (Sandbox Code Playgroud)
这段代码几乎可以工作,但它没有给出完整的答案。例如get_decimal(4.566666678258757587577)只返回:
0.566666678258757
Run Code Online (Sandbox Code Playgroud)
代替:
0.566666678258757587577
Run Code Online (Sandbox Code Playgroud)
有没有办法得到整数?
使用模数:
inp = 4.566666678258757587577
output = inp % 1
print(output) # prints 0.566666678259
Run Code Online (Sandbox Code Playgroud)
请注意,Python 的print()函数通常会尝试显示更易读的浮点数形式。因此,虽然打印的值似乎在 12 位后停止,但除了未显示之外还有更多的精度。
考虑:
print((output * 100000) % 1) # prints 0.667825875724
# 4.566666678258757587577 <- original input
Run Code Online (Sandbox Code Playgroud)