Python 小数位保留

#1#小数位保留“format()”:'{:.3f}'.format() & format(1.23456, '.2f')
'''
格式1:'{:.3f}'.format
格式2:format(1.23456, '.2f')
print('{:.3f}'.format(1.23456))
1.235
>>> print(format(1.23456, '.2f'))
1.23
正如上面代码所示,format有不同用法,格式1使用了占位符{},使用占位符可以同时输出多个,格式2只能输出一个,需要注意的是占位符中的冒号不能丢。
'''
#
# a=input('请输入数量:')
# b=input('请输入单价:')
# print('总计:%.2f' % (float(a)*float(b)))
# print('总计:','{:.2f}'.format(float(a)*float(b)))

#2#向上取整"ceil()"
import math
math.ceil(-0.5)
print(math.ceil(-0.5),math.ceil(0),math.ceil(2.5),math.ceil(3.1))
#输出结果:0 0 3 4

#3#向下取整“math.floor()”
print(math.floor(-0.3),math.floor(-1.5),math.floor(-2.5),math.floor(-3.6),math.floor(0),math.floor(2.3),math.floor(3.5),math.floor(4.5),math.floor(6.9))
#输出结果:-1 -2 -3 -4 0 2 3 4 6

#4#四舍五入“round()"
'''
(1)“四舍五入”中的“入”指的是往绝对值大的方向进位,而不是往数值大的方向进位;“舍”指的是往绝对值小的方向进位。
(2)若小数部分恰好等于 0.5 时,如果整数部分是偶数,那么采用“舍”的操作,往绝对值小的方向走;如果整数部分是奇数,那么采用“入”的操作,往绝对值大的方向走。
(3)小数位保留,格式:round(a,b)     "a"数值;“b"保留位数
'''
print(round(-1.2),round(-2.5),round(-3.5),round(-4.8),round(0),round(2.2),round(3.5),round(6.5),round(8.6))
print(round(-1.21,1),round(-2.56789,2),round(-3.54321,3),round(3.5,0),round(6.54321,1),round(8.6789,2))
#输出结果:-1 -2 -4 -5 0 2 4 6 9
#输出结果:-1.2 -2.57 -3.543 4.0 6.5 8.68


#5#向零取整“int()"
'''
数值小于零向上取整、数值大于零向下取整:取值方向指向0
'''
print(int(-0.1),int(-1.5),int(-2.5),int(-3.9),int(0),int(1.1),int(2.5),int(3.5),int(4.9))
#输出结果:0 -1 -2 -3 0 1 2 3 4

#小数保留N位进行四舍五入/向上取整/向下取整:“split()”分割函数

st='1234.56789'
zs,xs=str(st).split('.')
def int1(st):
    zs,xs=str(st).split('.')
    # print('第50行:',zs,xs)
    # print('zhengShu: {0}, xiaoShu: {1}'.format(str(zs),str(xs)))
    return 'zhengShu: {0}, xiaoShu: {1}'.format(str(zs),str(xs))
t=int1(st)
print('{name}{option}'.format(name=zs,option=xs))
print('{name}'.format(name=zs))

你可能感兴趣的:(Python,python,开发语言)