python的数字格式化输出问题(四舍五入保留小数) | 您所在的位置:网站首页 › python如何输出整数和浮点数 › python的数字格式化输出问题(四舍五入保留小数) |
内置函数round()使用介绍
使用round()函数实现数字的指定位数输出时需要格外注意,round()函数的实现效果与Python版本有关。不同版本的python中内置round()函数的功能不尽相同。 不同版本的python内置round()函数主要区别在于对输出的数字处理方式是截断(直接舍弃其余位)或者四舍五入原则。 举例说明round()函数的基本语法: >>> pi = 3.141592653589793 >>> round(pi) #输出整数 >>> round(pi, 2) #保留两位小数输出 >>> round(pi, 3) #保留三位小数输出以上程序的输出依Python版本不同而遵循不同原则。以python3.6(经验证python2.7也遵循四舍五入原则)为例,该版本python内置round()遵循四舍五入规则。故以上输出分别为3, 3.14和3.142。 PS:有关round()更多使用信息可查看python官方文档。 鉴于round()函数的版本依赖性,在实现数字指定位数输出时推荐使用下面的format方法。 format()方法介绍format方法是内置的python字符串格式化方法。基本语法为:str.format(),它增强了字符串格式化的功能。 基本语法是通过 {} 和 : 来代替以前的 % 。 format 函数可以接受不限个参数,位置可以不按顺序。 # 实例展示 >>>"{} {}".format("hello", "world") # 不设置指定位置,按默认顺序 'hello world' >>> "{0} {1}".format("hello", "world") # 设置指定位置 'hello world' >>> "{1} {0} {1}".format("hello", "world") # 设置指定位置 'world hello world'也可以设置参数或者向 str.format() 传入对象,此处重点介绍数字的格式化。 下表展示了 str.format() 格式化数字的多种方法: >>> print("{:.0f}".format(3.1415926)) 3 >>> print("{:.2f}".format(3.1415926)) 3.14 >>> print("{:.3f}".format(3.1415926)) 3.142
format的更多使用细节可参考python官方文档。 参考资料 菜鸟教程–format 格式化函数 |
CopyRight 2018-2019 实验室设备网 版权所有 |