当前位置:主页 > python教程 > python保留小数函数

python保留小数函数的几种使用总结

发布:2023-03-22 17:55:01 59


为网友们分享了相关的编程文章,网友隆理群根据主题投稿了本篇教程内容,涉及到python保留小数函数、python保留小数、python保留小数函数相关内容,已被273网友关注,如果对知识点想更进一步了解可以在下方电子资料中获取。

python保留小数函数

python保留小数——‘%f’

‘%.nf’% x(定义的变量)

例子:

a = 82.16332
print('%.1f'% a)
print('%.2f'% a)
print('%.3f'% a)
print('%.4f'% a)
print('%.10f'% a)

输出结果

python保留小数——format()函数

Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。

基本语法是通过 {} 和 : 来代替以前的 % 。

format 函数可以接受不限个参数,位置可以不按顺序。

例子

print("{:.1f}".format(0.167123))
print("{:.2f}".format(0.167123))
print("{:.3f}".format(0.167123))
print("{:.4f}".format(0.167123))
print("{:.10f}".format(0.167123))

输出结果

因为format()函数位置可以不按照顺序,所以也可以这样写

print(format(0.167123, '.1f'))
print(format(0.167123, '.2f'))
print(format(0.167123, '.3f'))
print(format(0.167123, '.10f'))

输出结果

通过观察数据可以发现上面两个数据都是进行‘四舍五入’的。

python保留小数——round()函数

round() 方法返回浮点数x的四舍五入值。

用法:round(数字,n),n为“数值表达式,表示从小数点位数”。

用例

s = 1.15457321
print("round(80.23456, 2) : ", round(80.23456, 2))
print( round(1203245, 3))
print(round(s,10))

输出结果

而对于round()函数有时候会出现一些问题,有时候无法提供正确的输出

例子

print(round(2.675,2))
print(round(8.875,2))

输出结果

如果按照’四舍五入‘的话应该是输出2.68的,但是结果是2.67,而8.875输出的是‘四舍五入’的值8.88

对于python round()函数

python中的舍入函数将十进制值四舍五入为给定的位数,如果我们不提供n(即十进制后的位数),则会将数字四舍五入为最接近的整数。

例子

#int
print(round(12))
#float
print(round(66.6))
print(round(45.5))
print(round(92.4))

输出结果

当提供第二个参数的时候,如果提供的参数n>=5的时候,则最后一个十进制数字将增加一,直至舍入后的值,不然的话将与提供的相同

例子

print(round(1.221, 2))
print(round(1.222, 2))
print(round(1.223, 2))
print(round(1.224, 2))
print(round(1.215, 2))
print(round(1.226, 2))
print(round(1.227, 2))
print(round(1.228, 2))
print(round(1.279, 2))

输出结果

可以看出是有的进位成功,有的是进位不成功的,所以这个round()函数不太好用,而对整数的进位是正确的

所以不建议使用这个方法

python保留小数——math.floor

floor() 返回数字的下舍整数。

使用floor的方法,需要引入math模块

floor()表示的是向下取舍

例子

import math
print("math.floor(-45.17) : ", math.floor(-45.17))
print("math.floor(100.12) : ", math.floor(100.12))
print("math.floor(100.72) : ", math.floor(100.72))
print("math.floor(119L) : ", math.floor(119))
print("math.floor(math.pi) : ", math.floor(math.pi))

输出结果

进行小数操作可以这样使用,先进行扩大数值的n次方,然后再除以n次方,即可得到’四舍五不入‘的数值

例子:(保留两位小数)

import math
print(math.floor(1.25754*10**2)/10**2)

输出结果

如果想要输出三位小数不进行‘四舍五入’,可以先乘10**3然后除以10**3

python保留小数——不进行四舍五入,简单粗暴法int()

例子

print(int(1.23456 * 1000) / 1000 )

输出结果

放大指定的倍数,然后取整,然后再除以指定的倍数。

可以利用上面的函数进行保留2位小数、3位小数、4位小数等

到此这篇关于python保留小数函数的几种使用总结的文章就介绍到这了,更多相关python保留小数函数内容请搜索码农之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持码农之家!


参考资料

相关文章

网友讨论