为了账号安全,请及时绑定邮箱和手机立即绑定

使用 python 将计算结果四舍五入到小数点后两位

使用 python 将计算结果四舍五入到小数点后两位

守着一只汪 2023-08-08 16:07:27
对编码和 Python 非常陌生。我试图将计算结果限制为小数点后两位,或者我想要的任意位数。通过 Google 发现了有关使用小数的信息,但我无法让我的代码正常工作。我从什么开始amount_per_day = amount_of_money/currency_amountprint("If you are going to spend " + str(amount_of_money) + " " + str(destination_currency) + " that means that you can spend up to " + str(amount_per_day) + " " + Home_currency + " per day to remain in budget.")我尝试过的from decimal import Decimalamount_per_day = Decimal(amount_of_money/currency_amount)amount_per_day_to_two_decimal_places = round(amount_per_day,2)print("If you are going to spend " + str(amount_of_money) + " " + str(destination_currency) + " that means that you can spend up to " + str(amount_per_day) + " " + Home_currency + " per day to remain in budget.")结果如果您打算花费 2000.0 欧元,这意味着您每天最多可以花费 1818.181818181818016455508768558502197265625 英镑以保持在预算之内。这些代码可以工作,但我不需要小数点后 39 位的答案。
查看完整描述

4 回答

?
倚天杖

TA贡献1828条经验 获得超3个赞

要四舍五入,您可以使用以下内容:

value = 1818.181818181818016455508768558502197265625
    print(round(value, 2))

您可以使用以下内容来设置文本格式。

print('you can spend %.2f GBP per day' % value)


查看完整回答
反对 回复 2023-08-08
?
侃侃尔雅

TA贡献1801条经验 获得超15个赞

只需使用你的变量在round(x, 2)哪里x



查看完整回答
反对 回复 2023-08-08
?
达令说

TA贡献1821条经验 获得超6个赞

一旦您计算出小数点后 39 位的 amount_per_day,您就可以使用内置函数“round”简单地删除它们


圆形的工作原理如下:round(float_num, num_of_decimals)

所以在你的情况下你会这样做amount_per_day = round(amount_per_day, 2)


我还建议您将 print 语句中添加的所有令人讨厌的字符串替换为 f 字符串,如下所示:


print(f"If you are going to spend {str(amount_of_money)}

      {str(destination_currency)} that means that you can

      spend up to {str(amount_per_day)} {Home_currency} per

      day to remain in budget.")

它看起来更干净而且实际上也更快


查看完整回答
反对 回复 2023-08-08
?
富国沪深

TA贡献1790条经验 获得超9个赞

Python 有一个内置函数round。文档中对此进行了深入介绍。

因此,就您而言,您正在寻找的结果是round(amount_per_day, 2). 请注意,这会将输出更改为小数点后两位(因此将有效地截掉第二个小数点后的剩余部分),并且即使在最接近值之间的中间,也会四舍五入到最接近的偶数值


查看完整回答
反对 回复 2023-08-08
  • 4 回答
  • 0 关注
  • 117 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信