Python之保留小数点后n位、向上取整、向下取整以及四舍五入函数
一、保留小数点后n位方法一:使用字符串格式化a = 12.3456print("%.3f"%a) #保留小数点后三位print("%.2f"%a) # 保留小数点后两位12.34612.35方法二:使用round内置函数a = 12.3456a1 = round(a,2) # 保留小数点后两位a2 = round(a,3) # 保留小数点后三位print(a1)print(a2)12.3512.3
·
一、保留小数点后n位
方法一:使用字符串格式化
注意:使用字符串格式化后的是字符串格式
a = 12.3456
print("%.3f"%a) #保留小数点后三位
print("%.2f"%a) # 保留小数点后两位
12.346
12.35
方法二:使用round内置函数
注意:使用round后的是浮点数格式
a = 12.3456
a1 = round(a,2) # 保留小数点后两位
a2 = round(a,3) # 保留小数点后三位
print(a1)
print(a2)
12.35
12.346
二、Python之向上取整、向下取整以及四舍五入函数
# ceil和floor都是在math库下面的
import math
f = 11.2345
# 向上取整
print(math.ceil(f))
# 向下取整,floor是地板代表向下取整
print(math.floor(f))
# 四舍五入
print(round(f))
12
11
11
更多推荐
已为社区贡献4条内容
所有评论(0)