我想在我的 f 字符串中设置精度,但我不希望小数部分尾随零。
i = 1002
print(f'{i/1000:.2f}') # 1.00 but this must be 1
i = 1009
print(f'{i/1000:.2f}') # 1.01, this is correct
Run Code Online (Sandbox Code Playgroud)
第一个print必须是1,我的预期行为在第二个中print可见1.01。
我尝试过:g,但它对第一个有效print,但对第二个失败。
i = 1000
print(f'{i/1000:.2g}') # 1, this is correct but
i = 1009
print(f'{i/1000:.2g}') # 1, but this must be 1.01
Run Code Online (Sandbox Code Playgroud)
我尝试过的一种方法是,f'{i/1000:.2f}'.strip('.0')但我想知道是否有更好的方法。
编辑 :
在我的实际代码中,如果i是100000,那么分母也将是 100000(按 顺序的最小数字i),换句话说,我的代码中的分母将始终是这样的,即 i// 分母将始终产生一个数字。