python - 如何摆脱Python减法中的额外 float ?

标签 python subtraction floating

def function():
    n=123.456
    x=int(n)
    y=n-int(n)
    print(x,y)

结果:

x= 123
y= 0.45600000000000307 

如何在不使用库函数的情况下精确获取.456n 可以是任意 float

最佳答案

如果您从一开始就知道小数位数是 3,那么:

y = round(n - int(n), 3)

如果您知道小数位数,那么您可以这样算出来:

y = round(n - int(n), str(n)[::-1].find('.'))

正如furas指出的,您还可以使用decimal包:

from decimal import Decimal

n = Decimal('123.456') 
y = n - int(n)

关于python - 如何摆脱Python减法中的额外 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58687240/

相关文章:

python - 将包含字符串数组的 .mat 文件加载到 Python 3.6

sql-server - 在 SQL Server 中减去两个时间值

html - 如何防止文本出现在图像后面

html - 响应式设计 : Float text over image

python - 将数据粘贴到 Pandas 数据框中

python - 如何从文本中提取国家?

python - 如何使用 numpy 从同一数组中减去两列并将值放入它们自己的单列数组中?

javascript - 如何制作 float 菜单 -> 位置 :static

python - Editra 0.7.08 是可靠的 IDE 吗?

python - 分配给数组元素的值结果为零