编程语言
首页 > 编程语言> > python中float类型小数点截取两种方法

python中float类型小数点截取两种方法

作者:互联网

练习:

输出你的身体指标:

身高:170

体重50.5

BMI指数:50.5/(170+50.5)

 

从上面可以看出,BMI指数是fload类型,如果需要保留两位小数,有两种写法

第一种写法,使用round()函数

#输出你的身体指标
height=170
weight=50.5
bmi=weight/(height+weight)
print('您的身高是:'+str(height))
print('您的体重是:'+str(weight))
print('您的BMI指数是:'+str(round(bmi,2)))

  执行结果:

 

 

 

第二种写法,使用format函数,代码如下:

#输出你的身体指标
height=170
weight=50.5
bmi=weight/(height+weight)
print('您的身高是:'+str(height))
print('您的体重是:'+str(weight))
print('您的BMI指数是:'+'{:0.2f}'.format(bmi))

  执行结果:

 

 

综上所述,round函数和format函数都可以对float类型的数据进行截取

 

标签:weight,python,float,小数点,height,50.5,str,print,170
来源: https://www.cnblogs.com/wx170119/p/14998675.html