Gabriel
Gabriel

Reputation: 42329

Strip trailing zeros from float while aligning with format()

I'm trying to store a float to file that can sometimes contain trailing zeros.

When appliyng {:g} the result is the expected: the trailing zeros are removed. The issue comes when I try to align the float in the text file, in this case I use {:>10.0g} and the result is the float written in scientific notation instead of just having its trailing zeros stripped.

Here's a MWE:

a = 546.0
b = 6785.35416

with open('format_test.dat', 'a') as f_out:
    f_out.write('{:g} {:>15.3f}'.format(a, b)) # <-- NO ZEROS BUT NOT ALIGNED
    f_out.write('\n')
    f_out.write('{:>10.0g} {:>15.3f}'.format(a, b)) # <-- ALIGNED BUT IN SC NOTATION

the output:

546        6785.354
     5e+02        6785.354

Is there any way to fix this from the format() end without having to tamper with the float before passing it on?

Upvotes: 0

Views: 329

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122024

g will automatically switch to scientific notation, depending on the magnitude of the value (see the docs). You can get what you want by using f for both values:

>>> '{:>10.0f} {:>15.3f}'.format(546.0, 6785.354)
'       546        6785.354'

Upvotes: 1

Related Questions