保留小数点后几位
e.g.
>>> print(format(1.23456, '.2f'))
1.23
• The .2 specifies the precision. It indicates that we want to round the number to two decimal places.
• The f specifies that the data type of the number we are formatting is a floating-point number.
Scientific Notation(科学计数法)
e.g.
>>> print(format(123.456, '.2e'))
1.23e+02
>>> print(format(123.456, '.2E'))
1.23E+02
Inserting Comma Separators(逗号分隔法)
>>> print(format(12345.6789, ',.2f'))
12,345.68
>>> print(format(12345.6789, ',f'))
12,345.678900
Specifying a Minimum Field Width(指定数字宽度)
# 以'x'填充参数右边,宽度为 12
>>> print("The weight is ", format(12345.6789, 'x<12.2f'), "Kg")
The weight is 12345.68xxxx Kg
# 以'x'填充参数左边,宽度为 12
>>> print("The weight is ", format(12345.6789, 'x>12.2f'), "Kg")
The weight is xxxx12345.68 Kg
Formatting a Floating-Point Number as a Percentage(百分比)
# 保留小数点后两位,以百分比表示
>>> print(format(0.62345, '.2%'))
62.34%
Formatting Integers(对整数格式化)
# 以'x'填充参数右边,宽度为15,逗号分隔,数字类型为整数
>>> print(format(123456789, 'x<15,d'))
123,456,789xxxx
参考文献
[1] Tony Gaddis,Starting Out with Python[M],United Kingdom: Pearson,2019
本文介绍了Python中使用format函数进行数字格式化的多种方法,包括保留小数位数、科学计数法显示、插入逗号分隔符、指定字段宽度及格式化为百分比等实用技巧。
&spm=1001.2101.3001.5002&articleId=97025845&d=1&t=3&u=6fbb20d9281b4bbda81872f6e8e85c41)
318

被折叠的 条评论
为什么被折叠?



