保留小数点后几位
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