|
本帖最后由 ttui 于 2014-5-25 15:21 编辑
网上有许多阿拉伯数字转中文大写数字的函数,最常见的是Num2Chi但其效果并不理想,很多情况都有错误,如100000000(一亿)会转换为“壹亿万元整”等,对金融机构来说其能正确转换的数字长度实在没法满足需求。为了用得踏实便自己写了一个,分享出来以供参考。
用法:Daxie(阿拉伯数字),数字不限长度,过长的数字请作为文本传递,如 Daxie("1000000030000030.231") ,转换结果为 壹千万亿零叁千万零叁拾元贰角叁分。
P.S. 二楼说的问题已解决,小数部分转换规则写错了,感谢一剑惊心
- Option Explicit
- Private NC(0 To 9) As String
- Private Units(0 To 5) As String
-
- Public Function Daxie(n As String) As String
- Dim i As Integer
-
- NC(1) = "壹": NC(2) = "贰": NC(3) = "叁"
- NC(4) = "肆": NC(5) = "伍": NC(6) = "陆"
- NC(7) = "柒": NC(8) = "捌": NC(9) = "玖"
- Units(0) = "千": Units(1) = "分": Units(2) = "角"
- Units(3) = "": Units(4) = "拾": Units(5) = "百"
-
- i = InStr(1, n, ".")
- If i > 0 Then
- Daxie = DaxieInt(Left(n, i - 1)) '转换整数部分
- Daxie = Daxie & IIf(Daxie <> "", "元", "") & DaxieDecimal(Right(n, Len(n) - i), Daxie <> "")
- Else
- Daxie = DaxieInt(n) '转换小数部分
- Daxie = Daxie & IIf(Daxie <> "", "元整", "")
- End If
- If Daxie = "" Then Daxie = "零"
- End Function
- Private Function DaxieDecimal(n As String, HasInt As Boolean) As String
- DaxieDecimal = DaxieDigSeg(Left(IIf(Len(n) < 2, n & "0", n), 2), 0) '小数部分仅转换前两位
- If Len(DaxieDecimal) = 2 Then
- DaxieDecimal = IIf(Right(DaxieDecimal, 1) = "分", IIf(hasInt, "零", "") & DaxieDecimal, DaxieDecimal & "整")
- End If
- End Function
- Private Function DaxieInt(n As String) As String
- Dim i As Integer, k As Integer, l As Integer
- Dim x As String
-
- l = Len(n)
- If l Mod 4 > 0 Then n = String(((l \ 4) + 1) * 4 - l, "0") & n '数的长度凑为4的整数倍
- l = Len(n) \ 4
- k = -1
- For i = 1 To l
- x = Mid(n, (i - 1) * 4 + 1, 4) '以4位为一段转换为中文大写
- If k Mod 10 = 0 Then '处理需要添零的情况
- DaxieInt = DaxieInt & IIf(x > 0, "零", "")
- ElseIf k > 0 And x < 1000 And x > 0 Then
- DaxieInt = DaxieInt & "零"
- End If
- If (l - i + 1) Mod 2 = 0 Then '加注单位
- DaxieInt = DaxieInt & DaxieDigSeg(x) & IIf(x > 0, "万", "")
- Else
- DaxieInt = DaxieInt & DaxieDigSeg(x) & IIf(i < l, "亿", "")
- End If
- k = x
- Next i
- End Function
- Private Function DaxieDigSeg(n As String, Optional uoffset As Integer = 2) As String '最长4位数字转为中文大写
- Dim i As Integer, j As Integer, k As Integer, l As Integer
-
- l = Len(n)
- k = -1
- For i = l To 1 Step -1
- j = Mid(n, i, 1)
- If j > 0 Then DaxieDigSeg = NC(j) & Units((l - i + 1 + uoffset) Mod 6) & IIf(k = 0 And DaxieDigSeg <> "", "零", "") & DaxieDigSeg
- k = j
- Next i
- End Function
复制代码
补充内容 (2014-6-6 20:59):
第12行的“千”应改为“仟”,13行的“百”应改为“佰”,唉,又犯低级错误了…… |
|