首页 > 编程知识 正文

python 如何保留两位小数,python怎样保留两位小数

时间:2023-05-05 16:04:15 阅读:244414 作者:733

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

文章目录: 一、保留两位小数 且 做四舍五入处理1、使用字符串格式化2、使用python内置的round() 函数3、使用python内置的decimal模块 二、保留两位小数 且 不做四舍五入处理1、使用序列中的切片2、使用re正则匹配模块 三、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 divisionimport osprint(2/3)

注意:

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


♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。