2

In some environments, exact decimals (numerics, numbers...) are defined with scale and precision, 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.

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

decimals.Decimal('1234.1')
decimals.Decimal('0.123')
Dschoni
  • 3,714
  • 6
  • 45
  • 80
  • If you want an exact number of decimal digits, then you really want an integer, and display it as if it were float? For example, dollar amounts being stored as integer pennies. – Kenny Ostrom Sep 12 '16 at 15:00
  • Well no. I want to store strings to a database. The database has strict formatting. I want to check if the strings match that formatting. – Dschoni Sep 12 '16 at 15:11

2 Answers2

2

The closest I could find in the 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

The decimal module doesn't seem to have the concept of scale. It's precision is basically your scale + your precision.

Jules G.M.
  • 3,624
  • 1
  • 21
  • 35
0

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.

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
Leonhard Printz
  • 355
  • 2
  • 16