Python:数字以及格式化输出

上一篇 / 下一篇  2017-08-14 09:53:51 / 个人分类:Python

格式化输出的形式:
1. 数字的四舍五入-round()函数
#第二个参数是保留的小数位数
round(1.23,1)
round(1.234354,3)
#为负数指的是向哪一位进行四舍五入
round(13344,-1)
round(132423,-4)

2. 精确的表示浮点数-decimal模块
主要是用在金融领域
from decimal import Decimal
a = Decimal('5.3')
b = Decimal('2.12')
print(a+b)
c = 5.3
d = 2.12
print((a+b) == 7.4)
#decimal模块允许控制计算的每一个方面
#首先创建本地上下文并且更改它的设置
#进入一个本地上下文
from decimal import localcontext
with localcontext() as ctx:
 ctx.prec = 3
 print(a/b)
with localcontext() as ctx:
 ctx.prec = 50
 a = Decimal('1.3')
 b = Decimal('1.7')
 print(a/b)

3. 数字的格式化输出
还是format好用
format形式
x = 1234.5454
print(format(x,'0.2f'))
#向右对齐
print(format(x,'>10.1f'))
#向左对齐
print(format(x,'<10.1f'))
print(format(x,'^10.1f'))
print(format(x,','))
print(format(x,'0,.1f'))
另一种format - str.format()
print('the value is {:0,.2f}'.format(x))
%来格式化数字
print('%0.2f'% x)
print('%10.1f'% x)
#左对齐
print('%-10.1f' % x)


TAG:

奇迹0901的个人空间 引用 删除 奇迹0901   /   2017-08-14 15:30:24
5
 

评分:0

我来说两句

Open Toolbar