【问题标题】:How to print a price with commas in python? [duplicate]如何在python中用逗号打印价格? [复制]
【发布时间】:2021-04-08 12:56:06
【问题描述】:

我有浮点数 12.200000,我需要使用字符串格式来输出 12,20。我怎么做? 我完全是初学者,我无法从文档中弄清楚。

【问题讨论】:

标签: python


【解决方案1】:

我就是这样做的:

flt = 12.200000
flt = str(flt)

if len(flt) == 4:
    flt += "0"
print(flt.replace(".", ","))

这样做的目的是首先将float 变成string。然后,我们检查字符串的长度是否为 4。如果是 4,我们在末尾添加一个零。最后,我们将. 替换为,。这给出了12,20 的所需输出。

【讨论】:

    【解决方案2】:

    如果你的值是一个浮点数,你可以简单地将它转换为字符串并使用 replace() 方法。

    value = 12.200000
    output = str(value).replace(".", ",")
    print(output)
    

    【讨论】:

      【解决方案3】:

      使用四舍五入将浮点数保留到小数点后两位。更换 .使用 a ,您需要将浮点数转换为字符串并使用 flt.replace('.',',') 来获得所需的答案。将其转换回浮点数据类型。

      flt = 12.200000
      flt = round(flt,2)
      flt = str(flt) 
      flt.replace('.',',') # Replace . with ,
      float(flt)  # 12,20
      

      【讨论】:

      • 没有任何解释的代码转储很少有帮助。 Stack Overflow 是关于学习的,而不是提供 sn-ps 来盲目复制和粘贴。请edit您的问题并解释它如何回答所提出的具体问题。见How to Answer
      【解决方案4】:
      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-27
        • 1970-01-01
        • 2017-11-22
        • 2023-01-17
        相关资源
        最近更新 更多