由网友(人穷脸丑农村户口)分享简介:值:预算=11,000实际=10,000差异=预算-实际(1,000)total, would be the value of budget variable: 11,000我的代码:percent_val = variance/totalformat_percent = {:.2f}.format(perce...![对比Excel 系列再添新成员,手把手教你用Python实现报表自动化](https://p.xsw88.cn/allimgs/daicuo/20230903/4663.png)
值: 预算=11,000 实际=10,000 差异=预算-实际(1,000)
total, would be the value of budget variable: 11,000
我的代码:
percent_val = variance/total
format_percent = {:.2f}.format(percent_val)
return format_percent
![对比Excel 系列再添新成员,手把手教你用Python实现报表自动化](https://p.xsw88.cn/allimgs/daicuo/20230903/4663.png)
我以为上面的代码会返回值9.09(小数点后两位)
return value: 9.09
此视频显示了它,但我看不到如何使用{0:2.df}字符串使其工作?
http://www.youtube.com/watch?v=mmJPx6YsOMI
如何将9.09%设置为数字而不是字符串的格式,以便以后可以使用它进行计算?
推荐答案
您忘记了生成字符串:
format_percent = '{:.2f}'.format(percent_val)
# ^ ^
另外,如果您想要百分比,则需要乘以100,如果您使用的是Python2(我说不清),则需要使用浮点数或from __future__ import division
。
如果您希望将数字四舍五入到小数点后两位,而不是创建格式化输出,则可以使用round
函数:
rounded = round(percent_val, 2)
然后,您的输出将是浮点型而不是字符串,并且您可以继续使用它进行数学运算。
相关推荐
最新文章