java java - 7 months ago 21
Python Question

Postgresql Numeric type display in python

I have a postgresql table with column defined as:

numeric(20,7)

If I insert the value
0
it saves it as:
0.0000000


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

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

Answer

You can format a Decimal simply by passing it to:

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

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'))
'0.0000000'
>>> '{:f}'.format(Decimal('0E-8'))
'0.00000000'
>>> '{:f}'.format(Decimal('0E-9'))
'0.000000000'

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

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

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