gpt4 book ai didi

Python字符串插值: only show necessary decimal places

转载 作者:bug小助手 更新时间:2023-10-28 10:48:14 24 4
gpt4 key购买 nike

如果我有例如 x = 40,我想要以下结果:

40"

对于 x = 2.5,结果应该是...

2.5"

所以我基本上想格式化到最多一位小数。我目前使用这个:

"{0:0.1f}\"".format(x, 1)

但这总是精确显示一位小数,这不是我真正想要的......

最佳答案

一个选项类似于

"{0}\"".format(str(round(x, 1) if x % 1 else int(x)))

如果没有小数部分,则将 x 显示为整数。很可能有更好的方法来解决这个问题。

关于Python字符串插值: only show necessary decimal places,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10507554/

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