python保留几位小数

  • 不进行四舍五入的方法 

decimal = 12.123456
#方法一:使用正则表达式(\.表示只能匹配到.    如果表达式里只写.表示匹配除了\n的任何字符)
import re
print(re.search(r"\d+\.\d{5}",str(decimal)).group())     #执行结果:12.12345

#方法二:使用序列中的切片
d1 = str(decimal).split(".")[0]     #d1="12"
d2 = str(decimal).split(".")[1]     #d2="123456"
d3 = d2[:5]       
print(float(d1+"."+d3))             #执行结果:12.12345

#方法三:放大指定的倍数,然后取整,然后再除以指定的倍数
print(int(decimal*100000)/100000)   #执行结果:12.12345

#方法四:使用函数str.partition("分隔符")
def get_specified_decimal(number,n):
    tuple1 = str(number).partition(".")    #返回的是一个3元的元组,第一个为分隔符左边的子串,第二个为分隔符本身,第三个为分隔符右边的子串
    return tuple1[0]+tuple1[1]+(tuple1[2]+"0"*n)[:n]    #(tuple1[2]+"0"*n):防止传入的小数位数小于要保留的位数 
print(get_specified_decimal(decimal,5))    #执行结果:12.12345
print(get_specified_decimal(12.12,5))      #执行结果:12.12000

 

  • 进行了四舍五入的方法

#方法一:使用字符串格式化("%.小数位数f" %数字)
print("%.5f" %decimal)          #执行结果:12.12346

#方法二:format(数字,".小数位数f")会进行四舍五入
print(format(decimal,".5f"))    #执行结果:12.12346

发布了14 篇原创文章 · 获赞 0 · 访问量 2480

猜你喜欢

转载自blog.csdn.net/weixin_44232308/article/details/103839264