【微筆記】C# 金額轉成國字

  • 502
  • 0
  • C#
  • 2020-03-28

C# 金額轉成國字

利用10的次方來處理,支援顯示最高單位,金額不足則補"零",話不多說,直接秀程式碼。

/// <summary>
/// 金額轉國字
/// </summary>
/// <param name="amount"></param>
/// <param name="amountUnit"></param>
/// <returns></returns>
public static string AmountToString(long amount, AmountUnit amountUnit)
{
    int length = amount.ToString().Length - 1;
    if (amount < 0)
    {
        throw new ArgumentOutOfRangeException("amount", "數值必須為正整數");
    }
    else if (length > 13)
    {
        throw new ArgumentOutOfRangeException("amount", "數值不可超過13位數");
    }

    if (amountUnit == 0 || length > (int)amountUnit)
    {
        amountUnit = (AmountUnit)length;
    }
    string[] numberTexts = { "零", "壹", "貳", "參", "肆", "伍", "陸", "柒", "捌", "玖" };
    string[] typeMappings = { "", "拾", "佰", "仟", "萬", "拾", "佰", "仟", "億", "拾", "佰", "仟", "兆" };
    long pow10, tempNum;
    List<string> result = new List<string>();
    for (int i = (int)amountUnit; i >= 0; i--)
    {
        pow10 = Convert.ToInt64(Math.Pow(10, i));
        tempNum = amount / pow10;
        amount -= tempNum * pow10;
        result.Add(numberTexts[tempNum]);
        if (typeMappings[i] != "")
        {
            result.Add(typeMappings[i]);
        }
    }
    return string.Join(" ", result);
}

/// <summary>
/// 顯示最高單位,不足補零
/// </summary>
public enum AmountUnit
{
    /// <summary>
    /// 開頭不補零
    /// </summary>
    NoPadding = 0,
    /// <summary>
    /// 拾
    /// </summary>
    Ten,
    /// <summary>
    /// 佰
    /// </summary>
    Hundred,
    /// <summary>
    /// 仟
    /// </summary>
    Thousand,
    /// <summary>
    /// 萬
    /// </summary>
    TenThousand,
    /// <summary>
    /// 拾萬
    /// </summary>
    HundredThousand,
    /// <summary>
    /// 佰萬
    /// </summary>
    Million,
    /// <summary>
    /// 佰萬
    /// </summary>
    TenMillion,
    /// <summary>
    /// 億
    /// </summary>
    HundredMillion,
    /// <summary>
    /// 拾億
    /// </summary>
    Billion,
    /// <summary>
    /// 佰億
    /// </summary>
    TenBillion,
    /// <summary>
    /// 仟億
    /// </summary>
    HundredBillion,
    /// <summary>
    /// 兆
    /// </summary>
    Trillion
}

 

結果

 

創用 CC 授權條款
本著作由Chenting Weng製作,以創用CC 姓名標示 4.0 國際 授權條款釋出。
This work by Chenting Weng is licensed under a Creative Commons Attribution 4.0 International License.
Based on a work at https://dotblogs.com.tw/chentingw.

部分文章內容會引用到其他網站的簡介或圖片,若有侵犯到您的著作權,請留言告知,本人會儘快移除。
免責聲明:文章屬個人記事使用,僅供參考,若引用文章造成一切損失,本人不承擔任何責任。如有錯誤,歡迎留言告知。

Part of the content of the article will refer to the profile or picture of other websites.
If there is any infringement of your copyright, please leave a message and let me remove it as soon as possible.
Disclaimer:The article is for personal use and is for reference only. I will not bear any responsibility for any loss caused by quoting the article. If there is an error, please leave a message to inform.