java
java

Reputation: 1214

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?

Upvotes: 2

Views: 2363

Answers (2)

Ilja Everilä
Ilja Everilä

Reputation: 52949

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".

Upvotes: 3

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181310

If you want to control the way a float number is formatted, you could try:

"{0:.2f}".format(n) # n is value read from db

Upvotes: 3

Related Questions