Python浮点数控制小数精度

将精度高的浮点数转换成精度低的浮点数。

1.round()内置方法

这个是使用最多的,刚看了round()的使用解释,也不是很容易懂。round()不是简单的四舍五入的处理方式。

For the built-in types supporting round(), values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done toward the even choice (so, for example, both round(0.5) and round(-0.5) are 0, and round(1.5) is 2).

 

 round()如果只有一个数作为参数,不指定位数的时候,返回的是一个整数,而且是最靠近的整数(这点上类似四舍五入)。但是当出现.5的时候,两边 的距离都一样,round()取靠近的偶数,这就是为什么round(2.5) = 2。当指定取舍的小数点位数的时候,一般情况也是使用四舍五入的规则,但是碰到.5的这样情况,如果要取舍的位数前的小树是奇数,则直接舍弃,如果偶数这 向上取舍。看下面的示例:

2. 使用格式化

效果和round()是一样的。

 

 

既然说到小数,就必然要说到整数。一般取整会用到这些函数:

1. round()

这个不说了,前面已经讲过了。一定要注意它不是简单的四舍五入,而是ROUND_HALF_EVEN的策略。

2. math模块的ceil(x)

取大于或者等于x的最小整数。

3. math模块的floor(x)

去小于或者等于x的最大整数。

 

posted @ 2016-02-17 14:23  aliy_pan  阅读(2241)  评论(0编辑  收藏  举报