如何将大浮点值转换为int? [英] How to convert large float values to int?
问题描述
我有一个包含大浮点数的变量,比如 a = 999999999999999.99
当我在解释器中输入 int(a)
时,它返回 1000000000000000
.对于像这样的长数字,如何获得 999999999999999
的输出?
999999999999999.99
是一个无法以浮点格式精确表示的数字,因此 Python 会妥协并选择最接近的值可以代表的.在这种情况下,恰好是 1000000000000000.这就是为什么将其转换为整数会得到 1000000000000000.
如果您需要比浮点数更高的精度,请考虑使用 decimal.Decimal
.
I have a variable containing a large floating point number, say a = 999999999999999.99
When I type int(a)
in the interpreter, it returns 1000000000000000
.
How do I get the output as 999999999999999
for long numbers like these?
999999999999999.99
is a number that can't be precisely represented in the floating-point format, so Python compromises and picks the closest value that can be represented. In this case, that happens to be 1000000000000000. That's why converting that to an integer gives you 1000000000000000.
If you need more precision than floats can provide, consider using decimal.Decimal
.
>>> import decimal
>>> a = decimal.Decimal("999999999999999.99")
>>> a
Decimal('999999999999999.99')
>>> int(a)
999999999999999
这篇关于如何将大浮点值转换为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!