欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

Python 中保留小数点后几位的方法

Python基础 迷途小书童 3年前 (2020-10-10) 2067次浏览 0个评论

软硬件环境

  • 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)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.13.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: round(1.245, 2)
Out[1]: 1.25

In [2]: round(1.235, 2)
Out[2]: 1.24

In [3]:

可以看到如果小数点后的第3位是0~4的话,那就直接舍掉;如果是6~9的话,那小数点后第2位就加1;如果是5的话,那就又要分情况了,当小数点后第2位是奇数时,那就加1,否则就保持不变。下图是官方的一个解释

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]: print("%.2f" % a)
5.68

In [3]:

此方法小数点后第3位是直接进行四舍五入运算的。

字符串切片操作

(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]: str(a).split('.')[0] + '.' + str(a).split('.')[1][:2]
Out[2]: '5.67'

In [3]:

使用 split 方法将小数点前后部分进行分割,小数点后部分直接取前2位数字,这里并没有进行四舍五入,最后再进行一次拼接。

喜欢 (0)

您必须 登录 才能发表评论!

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

请关闭 Adblock 等类似浏览器插件,然后刷新页面访问,感谢您的支持!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.