天天看点

python 大数字添加千分符

def NumberToStr(num, flag=True):
    try:
        if flag:
            num = int(num)
        else:
            num = float(num)
    except:
        return num
    if(type(float(1.1))==type(num)):
        str_num="%.2f"%num
    elif (type(int(1))==type(num)):
        str_num=str(num)
    else:
        return num
    left_len=length=len(str_num)
    right_len=0
    dot_cnt=str_num.count('.',0,length)
    if(dot_cnt!=0):#小数
        left_len=str_num.index('.',0,length)
        right_len=length-left_len
    cnt=left_len//3
    result=[]
    end=left_len
    while(cnt>0):
        result.append(str_num[end-3:end])
        end-=3
        cnt-=1
    result.append(str_num[:end])
    result.reverse()
    result_str=','.join(result)
    result_str+=str_num[left_len:]
    if(result_str[0]==','):
        return result_str[1:]
    else:
        return result_str