python中关于小数点后面的数四舍五入问题解决的几个函数供大家参考,现在问题是如何动态输入小数点后多少位,比如12.3000这样的

coding=utf-8
import decimal
def Newround(num,dpnum=0):
    str1=str(num)
    no=len(str1)
    count=0
    for i in str1:
        if i=='.':
            break
        elif 0<int(i)<10:
            count=count+1
        else:
            print "you input num is not int or float"
    if no - count <= dpnum:
        return float(str1)
    if no-count>dpnum:
        c=no-count-dpnum
        str2=str1[count+1:]
        str3=str1.replace(".",'')
        str4=str(round(int(str3), -(len(str2) - dpnum))).replace('.0','')[-len(str2):]
        str5=str(round(int(str3), -(len(str2) - dpnum))).replace('.0', '').strip(str4)
        return float(str5+'.'+str4)
###########################################################3
def Newround1(num,dpnum=0):
    str1=str(num)
    no=len(str1)
    count=0
    for i in str1:
        if i=='.':
            break
        elif 0<int(i)<10:
            count=count+1
        else:
            print "you input num is not int or float"

    # if no - count <= dpnum:
    num2= len(str1[count + 1:])
    num2=10**num2
    print num2
    return round(num*num2/num2,dpnum)
######################################################33
def roundX(num):
    num = str(num)
    num2 = num.split('.')
    if num2[1][2] < '5':
        result = float(num2[0] + '.' + num2[1][0:2])
    elif num2[1][2] <= '9':
        result = float(num2[0] + '.' + num2[1][0] + num2[1][1]) + 0.01
    result = '%.2f' % result
    return result
###################################################################33
def s4j5(a,num2):
    num2 = 10 ** num2
    a1=float(int(a*num2))
    tag=a*num2-a1
    if tag>=0.5:
     return((a1+1)/num2)
    else:
     return(a1/num2)
###########################
print Newround(11.33445,4)
print s4j5(11.9,4)
print format('%.4f' )%100.12

猜你喜欢

转载自blog.csdn.net/qq_41030861/article/details/79324424
今日推荐