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/ 量化
1、python2中除法,默认是取商,也就是在做除法的时候你是无法获取小数部分的!
如下:
2、解决方法,就是在脚本文件中开头导入未来版本功能,如下:
from __future__ import divisionimport osprint(2/3)注意:
from __future__ import division一定要在其他模块之前导入,否则报错!
♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠ ⊕ ♠