在日常使用中,会经常需要用Python对数字的输入和输出进行格式化处理,比如百分比、四舍五入后取整、保留几位小数等等,这里简单的介绍一下数字变量的输入及数据处理的常用几个方式。
详细函数使用教程可以看这篇博客:Python内置函数作用及解析
输入数字变量
python可定义单个变量值,也可以同时定义多个变量值。
a,b=1,2
[m,n]={3,4}
print (a)
print ([m,n])
print (m)
输出结果为:
1
[3, 4]
3
使用input()函数输入变量,支持单个变量,也可输入多个变量,如果想输入int类型的变量,可以在输入的同时定义int类型即可。
# 输入1个数字
a=int(input("please input:")
# 输入两个数字
a=int(input("please input:"))
b=int(input("please input:"))
# 一次性输入两个和以上数字:
a, b = map(int,input("please input:").split(','))
去小数取整
去小数取整可使用round函数,也可使用math函数。
区别在于:
- round() :为去掉小数四舍五入取整
- math.ceil():去掉小数位直接向上取整
- math.floor():去掉小数位直接向下取整
如下示例:
import math
#此为直接向上取整
print(math.ceil(1.522))
print(math.ceil(1.355))
#此为直接向下取整
print(math.floor(1.522))
print(math.floor(1.355))
#此为四舍五入取整
print(round(1.522))
print(round(1.355))
输出则为:
2
2
1
1
2
1
数字转化为百分比
print( '{:.2%}'.format(0.523))
输出为:
52.30%
保留小数位
保留小数位可以采用三种方式,分别是:
- 字符串格式化:%.2f
- round():
- decimal():
c=0.523
#第一种方式:使用字符串格式化
print("%.2f" %c )
#第二种方式:使用内置函数
print(round(c,2))
#第三种方式:使用decimal模块
from decimal import Decimal
print(Decimal(c).quantize(Decimal("0.00")))