使用python将数字(基于计算)格式化为百分比到小数点后两位

2024-05-23 18:48:57 发布

您现在位置:Python中文网/ 问答频道 /正文

价值观: 预算=11000 实际=10000 差异=预算-实际(1000)

total, would be the value of budget variable: 11,000

我的代码:

percent_val = variance/total
format_percent = {:.2f}.format(percent_val)
return format_percent

我以为上面的代码会重新输出值9.09(小数点后两位)

return value: 9.09

这个视频显示了它,但是我看不到使用{0:2.df}字符串使它工作?

http://www.youtube.com/watch?v=mmJPx6YsOMI

如何将9.09%格式化为数字而不是字符串,以便以后使用它进行计算?


Tags: ofthe字符串代码formatreturnvalueval
3条回答

你忘了做绳子了:

format_percent = '{:.2f}'.format(percent_val)
#                ^      ^

另外,如果您想要百分比,则需要乘以100,如果您使用的是Python 2(我不知道),则需要使用float或from __future__ import division

如果您想将数字舍入到小数点后两位,而不是创建格式化输出,那么有一个round函数:

rounded = round(percent_val, 2)

然后你的输出将是一个浮点数而不是一个字符串,你可以继续用它做数学运算。

如果您决定使用pandas和df,这里有一个quick method如果您不介意将所有pd数据设置为特定的精度,并且正如您所看到的,数据仍然可以使用其原始精度。

import pandas as pd
import numpy as np

pd.set_option('precision',2)
df = pd.DataFrame(np.random.randn(5,2), columns = ['A','B'])
df
Out[15]: 
      A     B
0 -1.87  1.20
1 -0.55 -1.19
2  1.04  0.89
3 -0.65  0.30
4  0.07 -1.37

df.A[0] + 1.77777
Out[16]: -0.095449113301297794

您可以将显示格式插入熊猫的显示选项:

In [11]: df = pd.DataFrame(np.random.randn(2, 2))

In [12]: df
Out[12]:
          0         1
0  1.058814 -0.011675
1 -0.002627 -0.152505

In [13]: pd.options.display.float_format = '{:.2f}'.format

In [14]: df
Out[14]:
      0     1
0  1.06 -0.01
1 -0.00 -0.15

有关python的字符串格式here的详细信息。

注意:数字本身不受影响(它们没有被舍入):

In [15]: df.iloc[0, 0]
Out[15]: 1.058814403984879

相关问题 更多 >