python浮点数保留两位小数_python如何保留指定小数点位数?

5eb4cca61a817368.jpg

python保留指定小数点位数的方法:

1、使用’%.2f’ %f 方法f = 1.23456

print('%.4f' % f)

print('%.3f' % f)

print('%.2f' % f)

结果:1.2346

1.235

1.23

这个方法会进行四舍五入

2、format函数

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {} 和 : 来代替以前的 % 。

1588907486816198.jpgprint(format(1.23456, '.2f'))

print(format(1.23456, '.3f'))

print(format(1.23456, '.4f'))

输出结果:1.23

1.235

1.2346

3、round()函数

round() 方法返回浮点数x的四舍五入值。

以下是 round() 方法的语法:round( x [, n] )

参数:

x -- 数值表达式。

n -- 数值表达式。a = 1.23456

b = 2.355

c = 3.5

d = 2.5

print(round(a, 3))

print(round(b, 2))

print(round(c))

print(round(d))

输出结果:1.235 # 1.23456最终向前进位了

2.35 # 2.355居然没进位

4 # 最终3.5居然变为4了

2 # 最终2.5取值变为2

更多Python知识请关注Python视频教程栏目。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值