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

对编码和 Python 非常陌生。我试图将计算结果限制为小数点后两位,或者我想要的任意位数。通过 Google 发现了有关使用小数的信息,但我无法让我的代码正常工作。


我从什么开始


amount_per_day = amount_of_money/currency_amount

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.")

我尝试过的


from decimal import Decimal

amount_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 位的答案。


守着一只汪
浏览 120回答 4
4回答

倚天杖

要四舍五入,您可以使用以下内容:value = 1818.181818181818016455508768558502197265625     print(round(value, 2))您可以使用以下内容来设置文本格式。print('you can spend %.2f GBP per day' % value)

侃侃尔雅

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

达令说

一旦您计算出小数点后 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.")它看起来更干净而且实际上也更快

富国沪深

Python 有一个内置函数round。文档中对此进行了深入介绍。因此,就您而言,您正在寻找的结果是round(amount_per_day, 2). 请注意,这会将输出更改为小数点后两位(因此将有效地截掉第二个小数点后的剩余部分),并且即使在最接近值之间的中间,也会四舍五入到最接近的偶数值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python