首页 > 解决方案 > 为什么使用 float() 会删除我格式化的小数位?

问题描述

我正在尝试编写一个比较运输成本的简单程序。我有一个默认的浮动值,它是溢价的,还有两个函数可以检查它,并根据用户的产品重量为用户提供最便宜的值。

我的代码如下:

premium_shipping = 125.00

def ground_shipping(weight):
  if weight <= 2.0 and weight >= 0:
    return float('{:.2f}'.format((weight * 1.50) + 20))
  elif weight > 2.0 and weight <= 6.0:
    return float('{:.2f}'.format((weight * 3.00) + 20))
  elif weight > 6.0 and weight <= 10.0:
    return float('{:.2f}'.format((weight * 4.00) + 20))
  elif weight > 10:
    return float('{:.2f}'.format((weight * 4.75) + 20))
  else:
    return "Your package doesn't weigh anything!"

def drone_shipping(weight):
  if weight <= 2.0 and weight >= 0:
    return float('{:.2f}'.format(weight * 4.50))
  elif weight > 2.0 and weight <= 6.0:
    return float('{:.2f}'.format(weight * 9.00))
  elif weight > 6.0 and weight <= 10.0:
    return float('{:.2f}'.format(weight * 12.00))
  elif weight > 10:
    return float('{:.2f}'.format(weight * 14.25))
  else:
    return "Your package doesn't weigh anything!"

def cheapest_shipping(weight):
  if ground_shipping(weight) < drone_shipping(weight) and ground_shipping(weight) < premium_shipping:
    return f'The cheapest shipping method is ground shipping. It would cost {ground_shipping(weight)} to ship your item.'
  elif drone_shipping(weight)  < ground_shipping(weight) and drone_shipping(weight) < premium_shipping:
    return f'The cheapest shipping method is drone shipping. It would cost {drone_shipping(weight)} to ship your item.'
  elif premium_shipping < ground_shipping(weight) and premium_shipping < drone_shipping(weight):
    return f'The cheapest shipping method is premium shipping. It would cost {premium_shipping} to ship your item.'
  else:
    return "Error. You have input an invalid weight."

print(ground_shipping(4.8))
# 34.4
print(cheapest_shipping(4.8))
# The cheapest shipping method is ground shipping. It would cost 34.4 to ship your item.
print(cheapest_shipping(41.5))

当我这样做时,从技术上讲,我得到了答案,但是我希望它位于小数点2位 当我包含float()时,它会将我的数字作为带有 1 个小数位的浮点数返回,我不确定如何将其更改为包含 2 个小数点。

提前致谢!

标签: pythonpython-3.xcontrol-flow

解决方案


、、和的float 之间没有区别。如果您想以某种方式呈现a ,最好在格式化时使用以下任何一种方式(按优先顺序):22.02.00000000000000000200e-2float

>>> pi = 3.14159

>>> f"{pi:.2f}"           # f-strings, introduced in Python 3.6.
'3.14'

>>> "{:.2f}".format(pi)   # str.format, use f-strings in preference.
'3.14'

>>> "%.2f" % (pi)         # VERY old method, avoid if possible.
'3.14'

如果您使用的是最新版本的 Python,那么 f-strings 是可行的方法。与%and不同str.format(),它们将数据项本地化到将在字符串中打印的位置,因此您不必在参数列表中搜索它。对比以下:

f"Hello, {name}, today is {dayOfWeek}"
"Hello, {}, today is {}".format(name, dayOfWeek)

推荐阅读