【发布时间】:2021-04-08 12:56:06
【问题描述】:
我有浮点数 12.200000,我需要使用字符串格式来输出 12,20。我怎么做? 我完全是初学者,我无法从文档中弄清楚。
【问题讨论】:
-
@KennethGithambo,这是千分位分隔符。 OP 希望用逗号而不是点来分隔小数部分。
标签: python
我有浮点数 12.200000,我需要使用字符串格式来输出 12,20。我怎么做? 我完全是初学者,我无法从文档中弄清楚。
【问题讨论】:
标签: python
我就是这样做的:
flt = 12.200000
flt = str(flt)
if len(flt) == 4:
flt += "0"
print(flt.replace(".", ","))
这样做的目的是首先将float 变成string。然后,我们检查字符串的长度是否为 4。如果是 4,我们在末尾添加一个零。最后,我们将. 替换为,。这给出了12,20 的所需输出。
【讨论】:
如果你的值是一个浮点数,你可以简单地将它转换为字符串并使用 replace() 方法。
value = 12.200000
output = str(value).replace(".", ",")
print(output)
【讨论】:
使用四舍五入将浮点数保留到小数点后两位。更换 .使用 a ,您需要将浮点数转换为字符串并使用 flt.replace('.',',') 来获得所需的答案。将其转换回浮点数据类型。
flt = 12.200000
flt = round(flt,2)
flt = str(flt)
flt.replace('.',',') # Replace . with ,
float(flt) # 12,20
【讨论】:
float = str(float)
#this converts the float to a string
float = float.replace(".", ",")
#this replaces the point with a comma
if len(float) == 4:
float += "0"
#this checks whether the float should end with a zero, and if it does it adds it
【讨论】: