把金額轉換為漢字表達式C#代碼

jopen 10年前發布 | 12K 次閱讀 C# .NET開發

/* 創建者:菜刀居士的博客

  • 創建日期: 2014年09月04號
  • 功能:Money類型轉換 /

namespace Net.String.ConsoleApplication { using System; using System.Collections.Generic;

public class MoneyHelper
{
    public static string[] chineseDigits = new string[] { "零", "壹", "貳", "叁", "肆", "伍", "陸", "柒", "捌", "玖" };

    /// <summary>
    /// 把金額轉換為漢字表示的數量,小數點后四舍五入保留兩位
    /// </summary>
    /// <param name="amount">小寫金額</param>
    /// <returns>人民幣大寫</returns>
    public static string amountToChinese(decimal amount)
    {
        if (amount > 99999999999999.99m || amount < -99999999999999.99m)
        {
            throw new Exception("參數值超出允許范圍 (-99999999999999.99 ~ 99999999999999.99)!");
        }
        // 如果是負數,先轉換為正數
        bool negative = false;
        if (amount < 0)
        {
            negative = true;
            amount = amount * (-1);
        }
        // 乘以100再進行四舍五入,實現小數保留2位
        decimal temp_r = Round(amount, 2);
        int temp = Convert.ToInt32(temp_r * 100);
        int numFen = (int)(temp % 10);    // 分
        temp = temp / 10;
        int numJiao = (int)(temp % 10);   // 角
        temp = temp / 10;
        // temp 目前是金額的整數部分
        //
        int[] parts = new int[20]; // 其中的元素是把原來金額整數部分分割為值在 0~9999 之間的數的各個部分
        int numParts = 0;          // 記錄把原來金額整數部分分割為了幾個部分(每部分都在 0~9999 之間)
        for (int i = 0; ; i++)
        {
            if (temp == 0)
            {
                break;
            }
            int part = (int)(temp % 10000);
            parts[i] = part;
            numParts++;
            temp = temp / 10000;
        }
        //
        bool beforeWanIsZero = true; // 標志“萬”下面一級是不是 0
        string chineseStr = "";
        for (int i = 0; i < numParts; i++)
        {
            string partChinese = partTranslate(parts[i]);

            if (i % 2 == 0)
            {
                if ("".Equals(partChinese))
                {
                    beforeWanIsZero = true;
                }
                else
                {
                    beforeWanIsZero = false;
                }
            }

            if (i != 0)
            {
                if (i % 2 == 0)
                {
                    chineseStr = "億" + chineseStr;
                }
                else
                {
                    // 如果“萬”對應的part為0,而“萬”下面一級不為0,則不加“萬”,而加“零”
                    if ("".Equals(partChinese) && !beforeWanIsZero)
                    {
                        chineseStr = "零" + chineseStr;
                    }
                    else
                    {
                        // 如果"萬"的部分不為0,而"萬"前面的部分小于1000大于0,則萬后面應該跟“零”
                        if (parts[i - 1] < 1000 && parts[i - 1] > 0)
                        {
                            chineseStr = "零" + chineseStr;
                        }
                        chineseStr = "萬" + chineseStr;
                    }
                }
            }
            chineseStr = partChinese + chineseStr;
        }

        // 最后處理
        if ("".Equals(chineseStr))  // 整數部分為 0, 則表達為"零元"
        {
            chineseStr = chineseDigits[0];
        }
        else if (negative)          // 整數部分不為 0, 并且原金額為負數
        {
            chineseStr = "負" + chineseStr;
        }
        chineseStr = chineseStr + "元";
        if ((numFen == 0) && (numJiao == 0))
        {
            chineseStr = chineseStr + "整";
        }
        else if (numFen == 0)  // 0 分,角數不為 0
        {
            chineseStr = chineseStr + chineseDigits[numJiao] + "角";
        }
        else                   // “分”數不為 0
        {
            if (numJiao == 0)
            {
                chineseStr = chineseStr + "零" + chineseDigits[numFen] + "分";
            }
            else
            {
                chineseStr = chineseStr + chineseDigits[numJiao] + "角" + chineseDigits[numFen] + "分";
            }
        }
        return chineseStr;
    }

    /// <summary>
    /// 把一個 0~9999 之間的整數轉換為漢字的字符串,如果是 0 則返回 ""
    /// </summary>
    /// <param name="amountPart"></param>
    /// <returns></returns>
    public static string partTranslate(int amountPart)
    {
        if (amountPart < 0 || amountPart >= 10000)
        {
            throw new Exception("參數必須是大于等于 0,小于 10000 的整數!");
        }

        string[] units = new string[] { "", "拾", "佰", "仟" };

        int temp = amountPart;

        string amountStr = amountPart.ToString();
        int amountStrLength = amountStr.Length;

        bool lastIsZero = true; // 在從低位往高位循環時,記錄上一位數字是不是 0
        string chineseStr = "";

        for (int i = 0; i < amountStrLength; i++)
        {
            if (temp == 0) // 高位已無數據
            {
                break;
            }
            int digit = temp % 10;
            if (digit == 0) // 取到的數字為 0
            {
                if (!lastIsZero) // 前一個數字不是 0,則在當前漢字串前加“零”字;
                {
                    chineseStr = "零" + chineseStr;
                }
                lastIsZero = true;
            }
            else   // 取到的數字不是 0
            {
                chineseStr = chineseDigits[digit] + units[i] + chineseStr;
                lastIsZero = false;
            }
            temp = temp / 10;
        }
        return chineseStr;
    }

    public static decimal Round(decimal data, int digits)
    {
        double i = Math.Pow(10, digits);
        decimal temp = (data * (decimal)(i));
        int intData = (int)temp;
        decimal digData = temp - intData;

        if (digData >= decimal.Parse("0.5"))
            intData++;
        string format = digits > 0 ? "0." : "0";
        for (int n = 0; n < digits; n++)
        {
            format += "0";
        }
        return Convert.ToDecimal(((decimal)(intData / i)).ToString(format));

    }

    /// <summary>
    /// 把金額轉換為漢字表示
    /// </summary>
    public static string RMBEncode(decimal num)
    {
        try
        {
            #region
            string str1 = "零壹貳叁肆伍陸柒捌玖";            //0-9所對應的漢字
            string str2 = "萬仟佰拾億仟佰拾萬仟佰拾元角分"; //數字位所對應的漢字
            string str3 = "";    //從原num值中取出的值
            string str4 = "";    //數字的字符串形式
            string str5 = "";  //人民幣大寫金額形式
            int i;    //循環變量
            int j;    //num的值乘以100的字符串長度
            string ch1 = "";    //數字的漢語讀法
            string ch2 = "";    //數字位的漢字讀法
            int nzero = 0;  //用來計算連續的零值是幾個
            int temp;            //從原num值中取出的值

            num = Math.Round(Math.Abs(num), 2);    //將num取絕對值并四舍五入取2位小數
            str4 = ((long)(num * 100)).ToString();        //將num乘100并轉換成字符串形式
            j = str4.Length;      //找出最高位
            if (j > 15) { return "溢出"; }
            str2 = str2.Substring(15 - j);   //取出對應位數的str2的值。如:200.55,j為5所以str2=佰拾元角分

            #endregion
            //循環取出每一位需要轉換的值
            for (i = 0; i < j; i++)
            {
                #region
                str3 = str4.Substring(i, 1);          //取出需轉換的某一位的值
                temp = Convert.ToInt32(str3);      //轉換為數字
                if (i != (j - 3) && i != (j - 7) && i != (j - 11) && i != (j - 15))
                {
                    #region
                    if (str3 == "0")
                    {
                        ch1 = "";
                        ch2 = "";
                        nzero = nzero + 1;
                    }
                    else
                    {
                        if (str3 != "0" && nzero != 0)
                        {
                            ch1 = "零" + str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                    }
                    #endregion
                }
                else
                {
                    #region
                    if (str3 != "0" && nzero != 0)
                    {
                        ch1 = "零" + str1.Substring(temp * 1, 1);
                        ch2 = str2.Substring(i, 1);
                        nzero = 0;
                    }
                    else
                    {
                        if (str3 != "0" && nzero == 0)
                        {
                            ch1 = str1.Substring(temp * 1, 1);
                            ch2 = str2.Substring(i, 1);
                            nzero = 0;
                        }
                        else
                        {
                            #region
                            if (str3 == "0" && nzero >= 3)
                            {
                                ch1 = "";
                                ch2 = "";
                                nzero = nzero + 1;
                            }
                            else
                            {
                                if (j >= 11)
                                {
                                    ch1 = "";
                                    nzero = nzero + 1;
                                }
                                else
                                {
                                    ch1 = "";
                                    ch2 = str2.Substring(i, 1);
                                    nzero = nzero + 1;
                                }
                            }
                            #endregion
                        }
                    }
                    #endregion
                }
                if (i == (j - 11) || i == (j - 3))
                {
                    ch2 = str2.Substring(i, 1);
                }
                str5 = str5 + ch1 + ch2;

                if (i == j - 1 && str3 == "0")
                {
                    str5 = str5 + '整';
                }
                #endregion
            }
            if (num == 0)
            {
                str5 = "零元整";
            }
            return str5;
        }
        catch
        {
            return "非法數據";
        }
    }

}

}</pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!