这个是使用最多的,刚看了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, andround(1.5) is 2).>>> round(2.5)3.0>>> round(-2.5)-3.0>>> round(2.675)3.0>>> round(2.675,2)2.67round()如果只有一个数作为参数,不指定位数的时候,返回的是一个整数,而且是最靠近的整数。一般情况是使用四舍五入的规则,但是碰到舍入的后一位为5的情况,如果要取舍的位数前的数是偶数,则直接舍弃,如果奇数这向上取舍。看下面的示例:>>> round(2.555,2)2.56>>> round(2.565,2)2.56>>> round(2.575,2)2.58>>> round(2.585,2)2.58
使用格式化
效果和round()是一样的。>>> a = ("%.2f" % 2.555)>>> a"2.56">>> a = ("%.2f" % 2.565)>>> a"2.56">>> a = ("%.2f" % 2.575)>>> a"2.58">>> a = ("%.2f" % 2.585)>>> a"2.58">>> a = int(2.5)>>> a2