简体   繁体   中英

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?

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM