1、向下取整int()

>>> a = 3.75
>>> int(a)
3

2、四舍五入round()

2.1 表达式:

round( x [, n] )

  • x – 数值表达式。
  • n – 数值表达式,表示从小数点位数。
print "round(80.23456, 2) : ", round(80.23456, 2)
print "round(100.000056, 3) : ", round(100.000056, 3)
print "round(-100.000056, 3) : ", round(-100.000056, 3)
  round(80.23456, 2) :  80.23
  round(100.000056, 3) :  100.0
  round(-100.000056, 3) :  -100.0
  • 当参数n不存在时,round()函数的输出为整数。
  • 当参数n存在时,即使为0,round()函数的输出也会是一个浮点数。
  • 此外,n的值可以是负数,表示在整数位部分四舍五入,但结果仍是浮点数。
print(round(123.45))
print(round(123.45,0))
print(round(123.45,-1))
123
123.0
120.0

2.2 注意:尽量不用round!,原因如下

在实际使用中发现round函数并不总是如上所说的四舍五入

round(2.355, 2)
2.35

因为该函数对于返回的浮点数并不是按照四舍五入的规则来计算,而会收到计算机表示精度的影响。

在python2.7的doc中,round()的最后写着,“Values are rounded to the closest multiple of 10 to the power minus ndigits; if two multiples are equally close, rounding is done away from 0.” 保留值将保留到离上一位更近的一端(四舍六入),如果距离两端一样远,则保留到离0远的一边。
所以round(0.5)会近似到1,而round(-0.5)会近似到-1

但是到了python3.5的doc中,文档变成了 " 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."
如果距离两边一样远,会保留到偶数的一边。
比如round(0.5)round(-0.5)都会保留到0,而round(1.5)会保留到2

特别注意以下两种情况:ref–>

  1. 如果保留位数的后一位如果是5,且5后面不再有数,要根据应看尾数“5”的前一位决定是舍去还是进入:如果是奇数则进入,如果是偶数则舍去。例如5.215保留两位小数为5.22; 5.225保留两位小数为5.22。
a=round(5.215,2)
b=round(5.225,2)
print('a={0} b={1}'.format(a,b))
	a=5.21 b=5.22
  1. 如果保留位数的后一位如果是5,且5后面仍有数。例如5.2254保留两位小数为5.23,也就是说如果5后面还有数据,则无论奇偶都要进入。
a=round(5.2254,2)
b=round(5.2153,2)
print('a={0} b={1}'.format(a,b))
	a=5.23 b=5.22

在这里插入图片描述Python3.8中的结果)

  1. 如果是一个数组元素:
import numpy as np
a=np.array([1.850,10])
round(a[0]/1.250)

在这里插入图片描述
得到的是一个数组浮点数

3、向上取整math.ceil()

>>> import math
>>> math.ceil(3.25)
4.0
>>> math.ceil(3.75)
4.0
>>> math.ceil(4.85)
5.0

4、分别取整数部分和小数部分


>>> import math
>>> math.modf(3.25)
(0.25, 3.0)
>>> math.modf(3.75)
(0.75, 3.0)
>>> math.modf(4.2)
(0.20000000000000018, 4.0)

有人可能会对最后一个输出结果感到诧异,按理说它应该返回 (0.2, 4.0) 才对。这里涉及到了另一个问题,即浮点数在计算机中的表示,在计算机中是无法精确的表示小数的,至少目前的计算机做不到这一点。

5、list元素取整

a=np.zeros(3)
a =list(map(int,a))
print(a)
type(a[0])

在这里插入图片描述

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐