2

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?

0

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

2 Comments

Can you explain the syntax? why .2?
@java .<precision>f sets the precision of the float. I think pablo chose 2 points arbitrarily.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.