如何在Python中将输出格式化为2位小数?

时间:2016-03-02 04:28:38

标签: python decimal

我正在尝试将输出格式化为Python中的2位小数。这是我的代码

show

因此,对于我的输出,我想将结尾格式化为2位小数。即,这2个变量 - (校长+ compoundAmount) - (principal + simpleAmount)

我知道我需要使用%。2,但我不知道如何将它添加到print语句中以便输出到2位小数...我该怎么做?

2 个答案:

答案 0 :(得分:2)

试试这个

print('pi is {:.2f}'.format(your_variable))

答案 1 :(得分:1)

您只需要简单的格式化字符串,例如: print('pi is %.2f' % 3.14159) 哪个输出为pi is 3.14

您可能想阅读https://docs.python.org/2.7/library/string.html#formatspec