python保留两位小数的3种方法实例
作者:Y_fulture 时间:2022-01-28 20:20:36
1.’%.2f’%f
该方法会进行四舍五入
代码如下所示:
f = 2.3456789
print('%.2f'%f)
print('%.3f'%f)
print('%.4f'%f)
结果如下所示
2.35
2.346
2.3457
2.format函数
该方法也会进行四舍五入
代码如下所示:
f = 2.3456789
print('{:.2f}'.format(f))
print('{:.3f}'.format(f))
print('{:.4f}'.format(f))
结果如下图所示
2.35
2.346
2.3457
3.round函数(不推荐使用)
round函数带有一点点的小坑,不是很推荐使用
round函数的进位规则一般为’四舍六入五凑偶’
代码如下图所示:
print(round(2.25,1))
print(round(2.35,1))
print(round(2.125,2))
print(round(2.875,2))
结果如下图所示:
2.2
2.4
2.12
2.88
这与我们的结论没有出入,但我们换一下数据,再看一下结果
print(round(2.335,2))
print(round(2.225,2))
2.33
2.23
这里就与我们的结论不一致,原因是在机器中浮点数不一定被精确的表达,在转换成01后可能为无限位,机器会进行截断处理,所以会和浮点数的精确值有一定的出入,从而达不到我们预期的目标
所以如果对浮点数没有精度要求时可以使用round函数
如果对浮点数的精度要求较高,推荐使用decimal模块
附:Python round() 函数
描述
round() 方法返回浮点数x的四舍五入值。
语法
以下是 round() 方法的语法:
round( x [, n] )
参数
x -- 数值表达式。
n -- 数值表达式,表示从小数点位数。
返回值
返回浮点数x的四舍五入值。
实例
以下展示了使用 round() 方法的实例:
#!/usr/bin/python
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
来源:https://blog.csdn.net/Yzy_fulture/article/details/111691871
标签:python,保留,小数
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Python中的进程操作模块(multiprocess.process)
2022-09-17 23:10:32
Web2.0 的视觉设计
2007-10-24 20:12:00
![](https://img.aspxhome.com/file/UploadPic/200710/24/20071024223710131s.jpg)
asp中如何过滤到单引号
2009-07-05 18:38:00
仿阿里巴巴搜索导航设计效果
2008-04-15 15:01:00
![](/images/sg_trans.gif)
python实现批量解析邮件并下载附件
2023-07-05 02:32:16
python实现录制全屏和选择区域录屏功能
2022-06-18 01:06:33
Python爬虫获取op.gg英雄联盟英雄对位胜率的源码
2024-01-02 13:03:52
![](https://img.aspxhome.com/file/2023/3/83933_0s.png)
Django权限机制实现代码详解
2022-09-18 01:21:51
详解基于Jupyter notebooks采用sklearn库实现多元回归方程编程
2022-04-19 21:35:31
![](https://img.aspxhome.com/file/2023/6/97036_0s.png)
Python利用matplotlib模块数据可视化绘制3D图
2023-07-25 07:48:24
![](https://img.aspxhome.com/file/2023/5/101155_0s.png)
Python3 模块、包调用&路径详解
2021-06-04 06:03:08
Python使用SQLite和Excel操作进行数据分析
2023-11-27 22:32:28
Photoshop设计制作网站流程图解
2007-10-25 12:06:00
![](https://img.aspxhome.com/file/UploadPic/200711/3/2007113203253675s.gif)
对python 匹配字符串开头和结尾的方法详解
2023-02-03 23:45:40
ASP教程:制作登陆验证页面程序
2008-10-23 15:00:00
九步学会Python装饰器
2021-04-05 15:35:07
JavaScript 获取客户端计算机硬件及系统信息
2009-01-13 17:59:00
![](https://img.aspxhome.com/file/UploadPic/20091/13/200901081050518738-49s.gif)
Oracle回滚段的概念,用法和规划及问题的解决
2010-07-26 13:08:00
thinkPHP中配置的读取与C方法详解
2023-11-14 17:12:35
Python 如何求矩阵的逆
2021-07-22 23:28:43
![](https://img.aspxhome.com/file/2023/7/72807_0s.jpg)