python 四舍五入

1. 方法1:round( )函数

round() 函数作用就是,返回浮点数x的四舍五入值。

> round( x [, n]  )
# 参数x,n均为数值表达式,返回值为x的四舍五入值。n为保留的小数位数,不加n则只保留x四舍五入后的整数部分。

>>> round(2.3)
2
>>> round(2.45, 1)
2.5
>>> round(2.675, 2)
2.67

# 解决方法(四舍六入五平分),但是这样可以解决部分浮点数四舍五入的问题,还是不可靠
>>> round(2.675 * 100)/100.0
2.68

2. 方法2: 使用decimal

>>> decimal.getcontext().rounding=decimal.ROUND_HALF_UP
>>> b=decimal.Decimal('37.045',decimal.getcontext())

>>> b.__round__(2)
>Decimal('37.05')

>>> b.__round__(3)
>Decimal('37.045')

>>> b.__round__(2)
>Decimal('37.05')

>>> b.__round__(1)
>Decimal('37.0')

>>> b=decimal.Decimal('37.065',decimal.getcontext())
>>> b.__round__(2)
>Decimal('37.07')

>>> b.__round__(1)
>Decimal('37.1')

3. 方法3: Decimal()+quantize()方法(推荐)

>>> import decimal
>>> from decimal import Decimal
>>> a = "1.345"
>>> a_t = Decimal(a).quantize(Decimal("0.00"), rounding=decimal.ROUND_HALF_UP)
>>> print(a_t)
1.35

>>> Decimal('1.115').quantize(Decimal('0.00'), rounding=decimal.ROUND_HALF_UP)
>>> Decimal('1.12')
>>> Decimal('0.125').quantize(Decimal('0.00'), rounding=decimal.ROUND_HALF_UP)
>>> Decimal('0.13')
  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值