Python基础---Formatting Numbers(对数字格式化)

保留小数点后几位

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值