python - 为什么使用 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 个小数点。
提前致谢!
解决方案
、、和的float
值 之间没有区别。如果您想以某种方式呈现a ,最好在格式化时使用以下任何一种方式(按优先顺序):2
2.0
2.00000000000000000
200e-2
float
>>> 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)
推荐阅读
- iis - IIS 10.0 AppPool 崩溃
- cmake - 扩展名为 .OBJ 的 CMake 和文本文件
- java - JSON值类型是否需要严格定义?
- c - Tic Tac Toe 2D Char Array 未在 row=0 中更新,col=0--C
- javascript - 在 Firestore 中创建排行榜
- python - 如何在猜数字游戏中添加不同级别和退出选项?
- php - 卡在数据库查询,laravel
- python - 在不聚合的情况下转置 Pandas DataFrame
- python - 如何获取每批中使用的数据的索引?
- c# - 如何根据包含在非唯一 XMLTag 中的唯一值定义智能 xPath,以便与 C# 中的 XmlNode.SelectNodes() 方法一起使用?