博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

c#将金额转换为大写,支持小数点,原创经典

Posted on 2014-03-10 17:40  悠子快跑  阅读(431)  评论(0编辑  收藏  举报

网上搜的都有问题,这个代码属于原创,代码简洁,支持小数点,若没有小数点,则为整

 

    /// <summary>
    /// 将金额转换成大写
    /// </summary>
    /// <param name="moneys">字符串金额</param>
    /// <returns></returns>
    public static string GetUpperMoney(string money)
    {
        int dotPos = money.IndexOf('.');//小数点位置
        string moneyRight = dotPos > -1 ? (money + "00").Substring(dotPos + 1, 2) : "";//小数部分
        if (dotPos > -1)
        {
            money = money.Substring(0, dotPos);//money取整
        }
        string rtnStr = "";
        string daxie = "元拾佰仟万亿";
        string daxieZ = "零壹贰叁肆伍陆柒捌玖";
        int moneyLen = money.Length;
        for (int i = 0; i < moneyLen; i++)
        {
            string nowStr = money.Substring(i, 1);
            string mn1 = daxieZ.Substring(Convert.ToInt32(nowStr), 1);
            int nowPos = moneyLen - i - 1;
            if (nowPos > 7)
            {
                if (nowPos == 8)
                {
                    nowPos = 5;
                }
                else
                {
                    nowPos = nowPos % 9 + 1;
                }
            }
            else if (nowPos > 4)
            {
                nowPos = nowPos % 5 + 1;
            }
            string mn2 = daxie.Substring(nowPos, 1);
            rtnStr = rtnStr + mn1 + mn2;
        }

        rtnStr = rtnStr.Replace("零仟", "");
        rtnStr = rtnStr.Replace("零佰", "");
        rtnStr = rtnStr.Replace("零拾", "");
        rtnStr = rtnStr.Replace("零零零", "");
        rtnStr = rtnStr.Replace("零零", "");
        rtnStr = rtnStr.Replace("零万", "");
        rtnStr = rtnStr.Replace("零亿", "亿");
        if (dotPos > 0)
        {
            rtnStr = rtnStr + daxieZ.Substring(Convert.ToInt32(moneyRight.Substring(0, 1)), 1) + "";
            rtnStr = rtnStr + daxieZ.Substring(Convert.ToInt32(moneyRight.Substring(1, 1)), 1) + "";
        }
        else
        {
            rtnStr += "";
        }
        return rtnStr;
    }