【问题标题】:How do I represent the return of a specific probability fraction to be shown as a float but limited to two decimal places? [duplicate]如何将特定概率分数的返回值表示为浮点数但限制为小数点后两位? [复制]
【发布时间】:2020-05-14 06:02:03
【问题描述】:

所以说我有一些看起来像这样的东西:

def probability_color():
  if color == 'red':
    return float(3/10)

所以本质上它应该返回 .30 而不是更长的时间。我的具体问题包括不像这个例子那样干净的分数,所以在这个特定的场景中我得到了很长的十进制浮点值。是否有一个简单的解决方案可以格式化它而不是使用类似 round() 的东西?

【问题讨论】:

标签: python python-3.x floating-point format decimal


【解决方案1】:

只需使用 Python 中的圆形格式来提供帮助。 这是改进后的代码:

def probability_color():
  if color == 'red':
    # Decimal places :)
    return float('%.2f' % (1/10))

【讨论】:

    猜你喜欢
    • 2023-01-08
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-11
    • 2011-11-18
    • 2022-01-11
    • 2018-03-04
    相关资源
    最近更新 更多