[英]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()
端修复此问题,而无需在传递前修改浮点数?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.