python string.format(),Python string.format()百分比,不取整

In the example below I would like to format to 1 decimal place but python seems to like rounding up the number, is there a way to make it not round the number up?

>>> '{:.1%}'.format(0.9995)

'100.0%'

>>> '{:.2%}'.format(0.9995)

'99.95%'

解决方案

If you want to round down always (instead of rounding to the nearest precision), then do so, explicitly, with the math.floor() function:

from math import floor

def floored_percentage(val, digits):

val *= 10 ** (digits + 2)

return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)

print floored_percentage(0.995, 1)

Demo:

>>> from math import floor

>>> def floored_percentage(val, digits):

... val *= 10 ** (digits + 2)

... return '{1:.{0}f}%'.format(digits, floor(val) / 10 ** digits)

...

>>> floored_percentage(0.995, 1)

'99.5%'

>>> floored_percentage(0.995, 2)

'99.50%'

>>> floored_percentage(0.99987, 2)

'99.98%'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值