在Python中将float转换为bigint时防止溢出的好方法是什么?

问题描述 投票:0回答:1

当修剪由于分割导致的大小数时,我遇到溢出问题。例如。:

>>> from math import floor
>>> int(100000000000000123.1)
100000000000000128
>>> floor(100000000000000123.1)
100000000000000128

从类型看来,数字是一个普通的浮点数,它不能以所需的精度存储。所以即使使用floor()我也会遇到同样的问题。是否有更好的数据类型来存储'长浮点/双打'?如果是的话,我如何强制bigints的划分不返回低精度浮点数?顺便说一句,我使用的是Python 3.6 64位。

python type-conversion integer-overflow
1个回答
0
投票

你想要stdlib模块decimal

import decimal

long_number = '100000000000000123.1'  # note that this is a string
your_decimal = decimal.Decimal(long_number)

Decimals非常聪明,可以从任何标准的数学运算中返回Decimal对象

result = your_decimal - 123
assert isinstance(result, decimal.Decimal)
assert your_decimal == decimal.Decimal('100000000000000000.1')
© www.soinside.com 2019 - 2024. All rights reserved.