数字的四舍五入
使用 round(value, ndigits)
#四舍五入1.23,保留1位小数
print(round(1.23, 1)) # 1.2
#四舍五入1.27,保留1位小数
print(round(1.27, 1)) # 1.3
#四舍五入-1.27,保留1位小数
print(round(-1.27, 1)) # -1,3
#四舍五入1.25361,保留3位小数
print(round(1.25361, 3)) # 1.254
#刚好在两个边界的中间的时候, round 函数返回离它最近的偶数
print(round(1.5)) # 2
print(round(2.5)) # 2
round() 函数的 ndigits 参数可以是负数,这种情况下,舍入运算会作用在
十位、百位、千位等上面
a = 19981231
print(round(a,-1)) # 19981230
print(round(a,-2)) # 19981200
print(round(a,-3)) # 19981000
精确的浮点数运算
使用 decimal.Decimal()
由于浮点数的一个普遍问题是它们并不能精确的表示十进制数。并且,即使是最简单的
数学运算也会产生小的误差,但有些业务必须分毫不差,需要此方法
from decimal import Decimal
a = Decimal('4.2')
b = Decimal('2.1')
print(a + b) # 6.3
print((a + b) == Decimal('6.3')) # True
数字的格式化输出
使用 format()
格式化输出单个数字的时候,可以使用此方法
a = 1234.567899
#2精度
print(format(a,'0.2f')) # '1234.57'
#10宽1精右对齐
print(format(a, '>10.1f')) # ' 1234.6'
#10宽1精左对齐
print(format(a, '<10.1f')) # '1234.6 '
#10宽1精中心对齐
print(format(a, '^10.1f')) # ' 1234.6 '
#包含千号分隔符
print(format(a, ',')) # '1,234.56789'
print(format(a, '0,.1f')) # '1,234.6'
#指数记法
print(format(x, 'e')) # '1.234568e+03'