Enforce precision in decimal python
<p>In some environments, exact decimals (numerics, numbers...) are defined with <code>scale</code> and <code>precision</code>, with scale being all significant numbers, and precision being those right of the decimal point. I want to use python's decimal implementation to raise an error, if the precision of the casted string is higher than the one defined by the implementation.</p>

<p>So for example, I have an environment, where <code>scale = 4</code> and <code>precision = 2</code>.
How can I achieve these commands to raise an error, because their precision exceeds that of the implementation?</p>

<pre><code>decimals.Decimal('1234.1')
decimals.Decimal('0.123')
</code></pre>

<p>You could always define a stricter class of Decimal and check the number of decimals in the setter and constructor functions. This should act exactly like the Decimal object, except that it'll raise a ValueError when its created or set with more than two decimals.</p>

<pre><code>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
</code></pre>

python decimal precision