Decimal support for NUMERIC field

Issue #56 resolved
Collin Anderson
created an issue

Can you add Decimal support to the NUMERIC field?

Comments (7)

  1. Matt Chaput repo owner

    Not really, because the purpose of the NUMERIC field is to use tricks to more efficiently store numbers with a fixed-length bit representation (float, int, and long).

    The best way I can think of for storing Decimals is to index them as strings padded to a fixed length with leading zeros so they sort properly, e.g.:

    Decimal("123.45") -> u"0000000123.45"

    Of course the downside is you have to decide ahead of time what's the biggest number you're going to need to index in order to know how much padding to use.

  2. Collin Anderson reporter

    What about doing something like:

    class DECIMAL(fields.NUMERIC):
        def __init__(self, decimal_places=2, **kwargs):
            self.decimal_places = decimal_places
            super(DECIMAL, self).__init__(Decimal, **kwargs)
        def Decimal_to_text(self, x):
            return self.int_to_text(int(x * (10 ** self.decimal_places)))
  3. Matt Chaput repo owner
    • changed status to open

    Yeah, that seems like it would work (as long as you accept the loss of decimal precision and the maximum value limit imposed by 32/64 bits). I guess I can add that to NUMERIC after all... Thanks for the tip :)

  4. Collin Anderson reporter

    I was just looking over the change set and noticed this:

    Decimal(s[:-4] + "." + s[-4:])

    Did you mean something like:

    Decimal(s[:-self.decimal_places] + "." + s[-self.decimal_places:])
  5. Log in to comment