gpt4 book ai didi

python - python - 如何连接四舍五入数字的字符串?

转载 作者:行者123 更新时间:2023-12-01 20:26:55 25 4
gpt4 key购买 nike

我无法找出在 python 中连接字符串的错误。

目标是将数字格式化为字符串,我可以以一致的长度打印该字符串。

我编写了以下代码:

def numPrint(number,roundplace):
num = round(number, roundplace)
if num > 0:
output = ('+' + str(num))
elif num < 0:
output = (str(num))
else:
output = (' 0.' + '0' * roundplace)

if len(output) < (3 + roundplace):
output2 = (output + '0')
else:
output2 = output

return output2

print(numPrint(0.001, 3))
print(numPrint(0, 3))
print(numPrint(-0.0019, 3))
print(numPrint(-0.01, 3))
print(numPrint(0.1, 3))

我希望它打印:

+0.001
0.000
-0.002
-0.010
+0.100

但是,我越来越

+0.001
0.000
-0.002
-0.010
+0.10

如何将“0”添加到最后一个以使其正常工作?

最佳答案

您只是忘记将 output2 乘以零:

if len(output) < (3 + roundplace):
output2 = (output + ('0'*(3 + roundplace - len(output))))
else:
output2 = output

或者,如果您不介意使用内置函数:

output2 = output.ljust(3 + roundplace, '0')

关于python - python - 如何连接四舍五入数字的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61053697/

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