新城旧梦

导航

C# 金钱 小写转大写的算法

调用 ConvertMoney的ConvertMoneyToWords(decimal money)方法即可

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace Common
{
    public class ConvertMoney
    {
        static string[] c_Num = { "", "", "", "", "", "", "", "", "", "" };
        static string[] c_FH = { "", "", "", "" };
        static string[] c_Wn = { "", "", "亿" };
        public static string ConvertMoneyToWords(decimal money)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(money.ToString()))
            {
                string[] moneysplit = money.ToString().Split(new string[] { "." }, StringSplitOptions.RemoveEmptyEntries);
                Regex reg = new Regex("零{2,}");
                string m = moneysplit[0];
                int mlen = m.Length;
                string word = string.Empty;
                for (int i = mlen; i > 0; i--)
                {
                    word = ConverNumToWord(word, m[mlen - i], i, true);
                }
                if (moneysplit.Length > 1)
                {
                    string d = moneysplit[1];
                    int dlen = d.Length > 2 ? 2 : d.Length;
                    if (dlen == 2 && d[0] == '0' && d[1] == '0')
                    {
                        word += "";
                    }
                    else
                    {
                        for (int i = 0; i < dlen; i++)
                        {
                            word = ConverNumToWord(word, d[i], i, false);
                        }
                    }
                }
                else
                {
                    word += "";
                }
                result = reg.Replace(word.ToString(), "");
            }
            return result;
        }
        private static string ConverNumToWord(string appendStr, char a, int index, bool isYuan)
        {
            string s = c_Num[Convert.ToInt32(a) - 48];
            if (isYuan)
            {
                int z = (index - 1) / 4;
                int y = (index - 1) % 4;
                appendStr = appendStr + s + (s != "" ? c_FH[y] : "");
                if (y == 0)
                {
                    appendStr = appendStr.Trim('') + c_Wn[z];
                }
            }
            else
            {
                if (index == 0 && s != "")
                {
                    appendStr = appendStr + s + "";
                }
                else if (index == 0)
                {
                    appendStr = appendStr + s;
                }
                if (index == 1 && s != "")
                {
                    appendStr = appendStr + s + "";
                }
            }
            return appendStr;
        }
    }
}

 

posted on 2016-06-14 11:55  新城旧梦  阅读(354)  评论(0编辑  收藏  举报