python 数字转人民币完整版

#把一个浮点数转为整数和小数部分
def divider(num):
    interger = int(num)
    #返回浮点数x的四舍五入值。
    fraction = round((num - interger)*100)
    return (str(interger),str(fraction))

han_list = ["零","壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"]
unit_list=["十","百","千"]
unit_decol_list = ["角", "分"]

#处理整数
def four_to_hanstr(num_str):
    result= ""
    num_len = len(num_str)
    for i in range(num_len):
        num = int(num_str[i])

        if i!=num_len-1 and num!=0:
            result +=han_list[num] + unit_list[num_len-2-i]
        else:
            result +=han_list[num]
    if '零零零零' in result:
        result = list(result)
        result.clear()

    elif '零零零' in result:
        if result[0] == '零':
            a = result.find('零零零')
            result = list(result)
            del result[a]
            del result[a]
        else:
            a = result.find('零零零')
            result = list(result)
            del result[a]
            del result[a]
            del result[a]

    elif '零零' in result:
        if result[-1] == '零':
            a = result.find('零零')
            result=list(result)
            del result[-1]
            del result[-1]

        else:
            a = result.find('零零')
            result = list(result)
            del result[a]
    elif result[-1]=='零':
        result =list(result)
        del result[-1]
    return ''.join(result)

#处理小数点
def newfraction(new_str):
    new_result =""
    num_len = len(new_str)
    for i in range(num_len):
        num = int(new_str[i])
        new_result += han_list[num] + unit_decol_list[i]
    return new_result


def interger_to_str(num_str):
    str_len = len(num_str)
    if str_len > 12:
        print("数字太大了翻译不了")
    elif str_len > 8:
        return four_to_hanstr(num_str[:-8])+"亿" + four_to_hanstr(num_str[-8:-4])+"万"+ four_to_hanstr(num_str[-4:])
    elif str_len > 4:
        return four_to_hanstr(num_str[:-4]) + "万" + four_to_hanstr(num_str[-4:])
    else:
        return four_to_hanstr(num_str)


def main(num=0):
    interger, fraction = divider(num)
    b = interger_to_str(interger)
    if len(b)> 0:
        b= b + '元'
    c="0"
    if int(fraction) > 0:
        c = newfraction(fraction)
    print(b + c)

if __name__ == '__main__':
        try:
            num = float(input("请输入一个浮点数:\n"))
            main(num)
        except ValueError as e:
            print("你输入了非法数字,请重新输入")

评论