对编码和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.181818181818016455508768558502197265625英镑来保持预算。
代码有效,但我不需要39位小数的答案。
只需使用round(x, 2)
,其中x
是您的变量
一旦用39位小数计算出amount_per_day,就可以使用内置函数"圆形";
圆形的工作方式如下:round(float_num, num_of_decimals)
所以在您的情况下,您执行amount_per_day = round(amount_per_day, 2)
我还建议你用这样的f-string替换你在打印声明中添加的所有讨厌的字符串:
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)
。请注意,这将把输出更改为小数点后2位(因此将有效地截断第二个小数点后的剩余小数点(,并且在偶数中四舍五入到最近的偶数值。
要取整,可以使用以下方法:
value = 1818.181818181818016455508768558502197265625
print(round(value, 2))
您可以使用以下内容设置文本格式。
print('you can spend %.2f GBP per day' % value)