简体   繁体   English

与format()对齐时,从float去除尾随零

[英]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. 应用{:g} ,结果是预期的:尾随的零被删除。 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. 当我尝试在文本文件中对齐浮点数时,问题就来了,在这种情况下,我使用{:>10.0g} ,结果是用科学记数法写的浮点数,而不是仅去除尾随零。

Here's a MWE: 这是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? 有什么办法可以在format()端修复此问题,而无需在传递前修改浮点数?

g will automatically switch to scientific notation, depending on the magnitude of the value (see the docs ). g会根据值的大小自动切换为科学计数法(请参阅docs )。 You can get what you want by using f for both values: 您可以通过对两个值都使用f来获得所需的值:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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