Python - 转换数字为大写货币格式

# 判断是否包含小数点,还有判断是否只包含小数点和数字的这边没写出来
def is_contain_dot(check_str):
    check_str = str(check_str)
    for ch in check_str:
        if ch == '.':
            return True
    return False


def money2chinese(moneystr):

    nums = {0: '', 1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '', 8: '', 9: ''}
    decimal_label = ['', '']
    small_int_label = {0: '', 1: '', 2: '', 3: '', 4: '', 5: '', 6: '', 7: '', 8: '亿'}
    decimal_part = ''
    integer_part_list = []
    integer_part = ''
    # 包含小数点,则分成整数部分和小数部分
    if is_contain_dot(moneystr) is True:
        integer, decimal = str(moneystr).split('.', 1)
        if len(decimal) > 2:
            # print('小数部分超出')
            return ('小数部分超出范围')
        elif len(integer) > 9:
            return ('还没见过这么多钱')
        # 处理小数部分,只处理到百分位
        for i, j in enumerate(decimal):
            """
            i: 记录循环次数
            """
            if j == '0' and decimal[-1] != '0':
                decimal_part += nums[int(j)]
            elif j == '0' and decimal[-1] == '0':
                pass
            else:
                decimal_part += (nums[int(j)] + decimal_label[i])
    # 不包含小数点,则为整数部分
    else:
        integer = str(moneystr)
        if len(integer) > 9:
            return ('还没见过这么多钱')

    """
    处理整数部分,到亿;这边的处理办法是从低位往高位读,遇到0,判断前一位是否为0,前一位为0的情况则不读,如果前一位不为0,则读0。
    """
    if integer != '' and int(integer) != 0:
        integer_part_list.insert(0, '')
    for n, m in enumerate(integer[::-1]):

        if n == 0 and m == '0':
            pass
        else:
            # 当前为0 同时在万位,并且输入不为0时插入“万”
            if m == '0' and n == 4 and int(integer) != 0:
                integer_part_list.insert(0, '')

            elif m == '0' and integer[::-1][n - 1] != '0':
                integer_part_list.insert(0, (nums[int(m)]))

            elif m == '0' and integer[::-1][n - 1] == '0':
                pass
            else:
                integer_part_list.insert(0, (nums[int(m)] + small_int_label[n]))
    integer_part = ''.join(integer_part_list)
    return (integer_part + decimal_part)

if __name__ == '__main__':
    print(money2chinese(float(233411738.24)))

 

posted @ 2020-08-25 11:17  pywjh  阅读(476)  评论(0编辑  收藏  举报
回到顶部