如何缩小 python 小数值的比例

How to reduce scale in python decimal value

我有一个小数值 Decimal('3.10E-7')。如何将其转换为 Decimal('3.1E-7)?

我有一些函数(我无法控制)返回第一个值。我正在尝试使用 fastavro 写入返回值,精度为 20,比例为 8。对于这个特定值,我收到错误

ValueError: Scale provided in schema does not match the decimal

因为比例是 9。

>>> Decimal('3.10E-7').as_tuple()
DecimalTuple(sign=0, digits=(3, 1, 0), exponent=-9)
>>> Decimal('3.1E-7').as_tuple()
DecimalTuple(sign=0, digits=(3, 1), exponent=-8)

我们如何将 Decimal('3.10E-7') 转换为 Decimal('3.1E-7)

Decimal.normalize 似乎符合您的要求:

Normalize the number by stripping the rightmost trailing zeros [...]

呼叫 Decimal('3.10E-7').normalize() returns Decimal('3.1E-7').