如何将大浮点值转换为int? [英] How to convert large float values to int?

查看:38
本文介绍了如何将大浮点值转换为int?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含大浮点数的变量,比如 a = 999999999999999.99

当我在解释器中输入 int(a) 时,它返回 1000000000000000.对于像这样的长数字,如何获得 999999999999999 的输出?

解决方案

999999999999999.99 是一个无法以浮点格式精确表示的数字,因此 Python 会妥协并选择最接近的值可以代表的.在这种情况下,恰好是 1000000000000000.这就是为什么将其转换为整数会得到 1000000000000000.

如果您需要比浮点数更高的精度,请考虑使用 decimal.Decimal.

<预><代码>>>>输入十进制>>>a = decimal.Decimal("999999999999999.99")>>>一种十进制('999999999999999.99')>>>内部(一)999999999999999

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆