python實現人民幣大寫轉換

2021-07-25 09:53:22 字數 2818 閱讀 6643

#!/usr/bin/python

# -*- coding:utf-8 -*-

# ********* 轉換方法介紹 *********

# 將需要轉換的數字從右向左,每4位分成乙個section,如:24530467103,將該數字拆分後,得到:

# 245 3046 7103 (245億3046萬7103)

# 對拆分後的數字先按照section進行數字到漢字的轉換,然後新增數值單位,如:仟,佰,拾,處理結束後可以得到轉換後的序列。

# 對section處理結束後,再對每個section進行單位的追加。如:兆、億、萬。

# 這裡需要注意一些特殊情況,如:section中連續出現0,最後乙個數字為0等。

debug = true

upper = ["零", "壹", "貳", "叄", "肆", "伍", "陸", "柒", "捌", "玖"]

decimal_unit = ["角", "分", "釐", "毫"]

section_unit = ["萬", "億", "兆"]

count_unit = ["拾", "佰", "仟"]

def dbg_print(s):

if debug:

print(s)

def split_num(num):

num_list =

if (len(num) <= 4):

return num_list

while (len(num)):

if (len(num) <= 4):

num_list.reverse()

return num_list

sec = num[-4:]

num = num[:-4]

# 處理小數部分,只支援4位,多於4位,四捨五入。

def convert_dec(num):

result = ""

count = 0

dbg_print(num)

for i in

num:

n = int(i)

if (0 != n):

result += upper[n]

result += decimal_unit[count]

count += 1

dbg_print(result)

return

result

# 處理整數部分

def convert_int(num):

section_list = split_num(num)

dbg_print(num)

dbg_print(section_list)

result = ""

sec_index = len(section_list) - 2

foritem

in section_list:

index = len(item) - 2

# 統計連續出現的數字0的個數。

flag = 0

# 計算遍歷過的item中的字元數。

count = 0

# 對每個section進行處理,得到數字對應的漢字。

for i in

item:

n = int(i)

if (0 == n):

flag += 1

else:

flag = 0

# 用來區分section的最後一位為0的情況

if (count != len(item)-1):

# 該位置的數字為0,並且它的下乙個數字非0。

if ((flag >= 1) and ('0' != item[count+1])):

result += upper[n]

else (0 != n):

result += upper[n]

else:

# section的最後乙個數字非0的情況。

if (0 != n):

result += upper[n]

# 最後乙個數字以及數字為0時,都不需要新增單位。

if ((index >= 0) and (0 != n)):

result += count_unit[index]

index += 1

count += 1

從第1個section開始,如果section中的數字不全為0,其後就需要新增section對應的單位。

if (sec_index >= 0

and flag != count):

result += section_unit[sec_index]

dbg_print(result)

sec_index -= 1

result = result.replace("壹拾", "拾")

result += "元"

return

result

# 轉換函式

def convert(num):

result = ""

num = round(float(num), 4)

integer,decimal = str(num).split('.')

result_int = convert_int(integer)

result_dec = convert_dec(decimal)

if (len(result_dec) == 0):

result = result_int += "整"

else:

result = result_int + result_dec

return

result

人民幣大寫轉換

人民幣大寫轉換 param numbervalue 人民幣小寫 return rmbcapital function numbervalue var chinesevalue 轉換後的漢字金額 var string1 零壹貳叄肆伍陸柒捌玖 漢字數字 var string2 萬仟佰拾億仟佰拾萬仟佰拾元...

pascal 人民幣大寫轉換

我們在程式設計的過程中,特別是開發和財務相關的應用程式的時候,幾乎都會遇到要將阿拉伯數字 一般是貨幣金額 轉換為中文大寫的要求。也有一些轉換程式,但大都不符合財務實際要求,比如最簡單的 function xd xx currency string var dx,ws string i,cd inte...

人民幣數字大寫轉換

中文大寫金額數字應用壹 貳 叄 肆 伍 陸 柒 捌 玖 拾 佰 仟 萬 億 元 角 分 零 整 正 等字樣。中文大寫金額數字到 元 為止的,在 元 之後,應寫 整 或 正 字,在 角 之後,可以不寫 整 或 正 字。中文大寫金額數字前應標明 人民幣 字樣,大寫金額數字有 分 的,分 後面不寫 整 或...