强制使用十进制精度 python

Enforce precision in decimal python

在某些环境中,精确小数(数字、数字...)用 scaleprecision 定义,小数位是所有有效数字,精度是小数点右边的那些.如果转换字符串的精度高于实现定义的精度,我想使用 python 的十进制实现来引发错误。

例如,我有一个环境,其中 scale = 4precision = 2。 我怎样才能实现这些命令来引发错误,因为它们的精度超过了实现的精度?

decimals.Decimal('1234.1')
decimals.Decimal('0.123')

我能找到的最接近的 decimal module is in the context.create_decimal_from_float example, using the Inexact context trap :

>>> context = Context(prec=5, rounding=ROUND_DOWN)
>>> context.create_decimal_from_float(math.pi)
Decimal('3.1415')
>>> context = Context(prec=5, traps=[Inexact])
>>> context.create_decimal_from_float(math.pi)
Traceback (most recent call last):
    ...
Inexact: None

小数模块好像没有刻度的概念。它的精度基本上是你的比例+你的精度。

您始终可以定义更严格的 class 小数并检查 setter 和构造函数中的小数位数。这应该与 Decimal 对象完全一样,除了它会在创建或设置超过两位小数时引发 ValueError。

class StrictDecimal:
    def __init__(self, x):
        x = Decimal(x)
        if format(x, '.2f') != str(x):
            raise ValueError('Precision must by limited to 2 digits')
        self._x = x

    @property
    def x(self):
        return self._x

    @x.setter
    def x(self, x):
        x = Decimal(x)
        if format(x, '.2f') != str(x):
            raise ValueError('Precision must by limited to 2 digits')
        self._x = x