java java - 2 years ago 81
Python Question

Postgresql Numeric type display in python

I have a postgresql table with column defined as:


If I insert the value
it saves it as:

When I assign this value to Python (2.7) it shows me
which is correct but a wrong format.

Why does it shows it like this? and how can I fix it?

Answer Source

You can format a Decimal simply by passing it to:


The Decimal supports advanced string formatting:

# PEP 3101 support.  the _localeconv keyword argument should be
# considered private: it's provided for ease of testing only.
def __format__(self, specifier, context=None, _localeconv=None):
    """Format a Decimal instance according to the given specifier.

    The specifier should be a standard format specifier, with the
    form described in PEP 3101.  Formatting types 'e', 'E', 'f',
    'F', 'g', 'G', 'n' and '%' are supported.  If the formatting
    type is omitted it defaults to 'g' or 'G', depending on the
    value of context.capitals.

By default it seems to use the precision of the Decimal itself:

>>> '{:f}'.format(Decimal('0E-7'))
>>> '{:f}'.format(Decimal('0E-8'))
>>> '{:f}'.format(Decimal('0E-9'))

If on the other hand you want to use a custom precision, pass it in the format string:

>>> print("{:.2f}".format(Decimal("0E-7")))

For an explanation on what the different letters in the format mean, consult the "Format Specification Mini-Language".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download