如何将特定概率分数的 return 表示为浮点数但限于小数点后两位?

How do I represent the return of a specific probability fraction to be shown as a float but limited to two decimal places?

所以说我有这样的东西:

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

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

只需使用 Python 中的圆形格式即可。 这是改进后的代码:

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