How do I expand a long number (ending in e+##) to show in expanded form?
Asked Answered
W

2

5

So, this may be a simple question but I'm having some trouble finding the answer anywhere.

Take for example I have a simple program where I want to divide a by b like so:

def main():
    a = 12345678900000000
    b = 1.25

    answer = (a / b)
    print(answer)
main()

This particular example would result in 9.87654312e+15. How do I get Python to ignore simplifying my number and just give me the whole number?

Thanks in advance, sorry if it's really basic, I wouldn't have asked if I could have found it through Google.

Waterbuck answered 31/5, 2014 at 13:9 Comment(0)
R
6

You are seeing the default str() conversion for floating point numbers at work. You can pick a different conversion by formatting the number explicitly.

The format() function can do this for you:

>>> n = 9.87654312e+15
>>> format(n, 'f')
'9876543120000000.000000'

See the Format Specification Mini-Language documentation for more options. The 'f' format is but one of several:

Fixed point. Displays the number as a fixed-point number. The default precision is 6.

The default precision resulting in the .000000 six digits after the decimal point; you can alter this by using .<precision>f instead:

>>> format(n, '.1f')
'9876543120000000.0'

but take into account that decimals are rounded to fit the requested precision.

The g format switches between using exponents (e) and f notation, depending on the size of the number, but won't include decimals if the number is whole; you could use a very large precision with 'g' to avoid printing decimals altogether:

>>> format(n, '.53g')
'9876543120000000'

To be explicit, str(n) is the same as format(n, '.12g'), repr(n) is format(n, '.17g'); both can use the exponent format when the exponent is larger than the precision.

Rely answered 31/5, 2014 at 13:11 Comment(4)
repr(n) might also be an optionLuxemburg
@JonClements: but that's another default format without much control.Rely
That's why I said might - at least the precision doesn't require specifying .1f which might truncate in cases where more is required... depends how explicit the OP wishes to be... so that's why it might be okay :)Luxemburg
@JonClements: repr() is format(n, '.17g'), which happens to work for this number, but if the exponent were higher it'll still be shown.Rely
T
1

just be more specific about the floating point format

>>> print answer
9.87654312e+15
>>> print "%.20f" % answer
9876543120000000.00000000000000000000
Thoma answered 31/5, 2014 at 13:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.