python保存两位小数的几种方法,python2保留小数

一、保留两位小数 且 做四舍五入处理

1、使用字符串格式化


>>> x = 3.1415926
>>> print("%.2f" % x)
3.14
>>>

2、使用python内置的round() 函数

>>> x = 3.1415926
>>> round(x, 2)
3.14
>>>

round()函数的官方定义:

def round(number, ndigits=None): # real signature unknown; restored from __doc__
    """
    round(number[, ndigits]) -> number
    
    Round a number to a given precision in decimal digits (default 0 digits).
    This returns an int when called with one argument, otherwise the
    same type as the number. ndigits may be negative.
    """
    return 0

3、使用python内置的decimal模块

decimal 英 /'desɪm(ə)l/ 小数的
quantize 英 /'kwɒntaɪz/ 量化

>>> from decimal import Decimal
>>> x = 3.1415926
>>> Decimal(x).quantize(Decimal("0.00"))
Decimal('3.14')
>>> a = Decimal(x).quantize(Decimal("0.00"))
>>> print(a)
3.14
>>> type(a)
<class 'decimal.Decimal'>
>>> b = str(a)
>>> b
'3.14'

二、保留两位小数 且 不做四舍五入处理

1、使用序列中的切片

>>> x = 3.1415926
>>> str(x).split(".")[0] + "." + str(x).split(".")[1][:2]
'3.14'

2、使用re正则匹配模块

>>> import re
>>> x = 3.1415926
>>> re.findall(r"\d{1,}?\.\d{2}", str(a))
['3.14']

三、python2保留小数

1、python2中除法,默认是取,也就是在做除法的时候你是无法获取小数部分的!

如下:

在这里插入图片描述

2、解决方法,就是在脚本文件中开头导入未来版本功能,如下:

from __future__ import division
import os

print(2/3)

在这里插入图片描述

注意:

from __future__ import division一定要在其他模块之前导入,否则报错!

在这里插入图片描述


在这里插入图片描述


在这里插入图片描述
♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值