如何从小数点中删除尾随零并使用 Python 格式化货币

How to drop trailing zeros from decimal and format a currency using Python

我尝试从小数点中删除尾随零并使用此代码格式化货币

def dropzeros_with_comma(num):
    return "{:,}".format(num)

当 num 为 2220.80 时有效 returns 2,220.8

但是当 num 为 2220.00 时 returns 2,220.0 我只想要 2,220

谁能帮忙

我认为没有特定的格式;您可以手动删除“.0”:

def dropzeros_with_comma(num):
    s = "{:,}".format(num)
    if s.endswith(".0"):
        return s[:-2]
    else:
        return s