Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在使用python的计算中,将计算结果四舍五入到小数点后两位_Python_Decimal_Rounding - Fatal编程技术网

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

在使用python的计算中,将计算结果四舍五入到小数点后两位,python,decimal,rounding,Python,Decimal,Rounding,非常新的编码和Python。我试图将计算结果限制在小数点后两位,或者任意多。通过谷歌发现了使用小数的问题,但我的代码无法正常工作 我从什么开始 amount_per_day = amount_of_money/currency_amount print("If you are going to spend " + str(amount_of_money) + " " + str(destination_currency) + " that mea

非常新的编码和Python。我试图将计算结果限制在小数点后两位,或者任意多。通过谷歌发现了使用小数的问题,但我的代码无法正常工作

我从什么开始

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.181818016455508768558502197265625英镑,以保持在预算内


代码可以工作,但我不需要39位小数的答案。

只要使用
round(x,2)
其中
x
是您的变量

一旦您用39位小数计算出每天的金额,您就可以使用内置函数“round”将其删除

round的工作原理如下:
round(float\u num,num\u of\u decimals)

因此,在您的情况下,您需要
amount\u per\u day=round(amount\u per\u day,2)

我还建议您将打印语句中添加的所有讨厌的字符串替换为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有一个内置函数。文档中对其进行了深入介绍


因此,在您的情况下,您要查找的结果是
轮(每天的金额,2)
。请注意,这会将输出更改为小数点后2位(因此将有效地截断第二个小数点后的剩余小数点),并将舍入到最接近的偶数值,即最接近的值之间的中间值。

要舍入,可以使用以下方法:

value = 1818.181818181818016455508768558502197265625    
print(round(value, 2))
您可以使用以下命令设置文本格式

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

两条评论:您的帖子格式不正确,请编辑。另外,在发帖前做些调查,你的问题的答案在谷歌上只需点击一下!