【问题标题】:When rounding integer, don't add to the end [duplicate]舍入整数时,不要添加到末尾[重复]
【发布时间】:2021-06-24 23:16:12
【问题描述】:

我目前正在尝试使用具有可变小数位长度的数字。它可以是整数,也可以是最多 10 位小数,即 33.3333333。我想限制数字在超过长度时只有 2 位小数,或者如果它更少,则保持原始数字。

我尝试过使用"{:0:.2f}".format,但问题是对于整数,它还会在字符串末尾添加 .00。

当我尝试使用 round(3) 时,它会返回 3.0。

有没有一种方法,最好是单行,可以将 3.333333 转换为 3.33,但仍允许 3 保留为 int?

【问题讨论】:

  • 您使用的是 Python 2 吗?因为round(3) 在 Python 3 中返回 3,而不是 3.0。您可能应该升级(Python 2 在一年半前结束生命周期)。

标签: python integer decimal rounding


【解决方案1】:

尝试根据值完整性选择格式:

"{d}" if int(a) == a else "{:0:.2f}"

你能从那里完成吗?

【讨论】:

    【解决方案2】:

    您可以使用conditional expression 根据变量的类型选择格式:

    for x in (33.3333333, 3):
        print(("{:0}" if isinstance(x, int) else "{:.2f}").format(x))
    

    您还可以使用字典来实现它,将类型映射到格式字符串:

    formats = {int: "{:0}", float: "{:.2f}"}
    
    for x in (33.3333333, 3):
        print(formats.get(type(x)).format(x))
    

    【讨论】:

      猜你喜欢
      • 2016-08-14
      • 1970-01-01
      • 2012-11-01
      • 2014-05-11
      • 1970-01-01
      • 2012-02-24
      • 2023-04-07
      • 2013-11-25
      • 1970-01-01
      相关资源
      最近更新 更多