软硬件环境
windows 10 64bit
anaconda3 with python 3.7
前言
编程过程中经常会遇到将float类型数据进行截取,也就是只保留小数点后几位的情况。本文以保留小数点后2位为例,介绍几种常用的实现方法。
round方法
(base) PS C:\Windows\system32> ipython Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help.
In [1]: a = 5.6789
In [2]: round(a, 2)
Out[2]: 5.68
In [3]:
可以看到,此方法在保留小数点后2位的情况下,小数点第3位是进行了四舍五入的运算的。
但是,需要注意的是,round方法并不是真的四舍五入,来看下面的测试
(base) PS C:\Windows\system32> ipython Python 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]