gpt4 book ai didi

python - 在python中,我想要数千个单独的十进制数并精确显示2个十进制数字

转载 作者:行者123 更新时间:2023-12-01 07:51:27 24 4
gpt4 key购买 nike

考虑以下数字:

1000.10
1000.11
1000.113

我想让这些在 python 中打印出来:

1,000.10
1,000.11
1,000.11

以下转换几乎可以做到这一点,只不过每当小数点右侧的第二位数字为零时,该零就会被忽略,从而导致数字无法正确排列。

这是我的尝试:

for n in [1000.10, 1000.11, 1000.112]:
nf = '%.2f' %n # nf is a 2 digit decimal number, but a string
nff = float(nf) # nff is a float which the next transformation needs
n_comma = f'{nff:,}' # this puts the commas in
print('%10s' %n_comma)

1,000.1
1,000.11
1,000.11

有没有办法避免省略第一个数字中的结尾零?

最佳答案

您需要格式说明符',.2f'。正如您所指出的,, 执行千位逗号分隔,而 .2f 指定要保留两位数字:

print([f'{number:,.2f}' for number in n])

输出:

['1,000.10', '1,000.11', '1,000.11']

关于python - 在python中,我想要数千个单独的十进制数并精确显示2个十进制数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56194991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com