金额转大写

来源:https://www.917118.com/tool/rmb.html 页面的js中有,我将其转化成了php的方法。

//转大写金额
    function moneyToString($num)
    {
        //分割整数和小数
        $parts = explode('.', $num);
        $arrlong = count($parts);
        if ($arrlong > 1) {
            $integral = $parts[0];
            $decimal = $parts[1];
            $decimal = substr($decimal,0,2);
        }
        else {
            $integral = $parts[0];
            $decimal = "";
        }
        // 最长整数12位(千亿)
        if (strlen($integral) > 12) {
            $integral = substr($integral,0,12);
        }
        if ($decimal == '00') {
            $decimal = '';
        }
        // 设置大写数字及单位
        $CN_ZERO = "零";
        $CN_SYMBOL = "";
        $CN_DOLLAR = "元";
        $CN_INTEGER = "整";
        $digits = array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖");
        $radices = array("", "拾", "佰", "仟");
        $bigRadices = array("", "万", "亿");
        $decimals = array("角", "分");
        $outputCharacters = "";
        // 处理整数
        if ($integral > 0) {
            $zeroCount = 0;
            $strlong = strlen($integral);
            for ($i = 0; $i < $strlong; $i++) {
                $p = $strlong - $i - 1;
                $d = substr($integral,$i, 1);
                $quotient = $p / 4;
                $modulus = $p % 4;
                if ($d == "0") {
                    $zeroCount++;
                } else {
                    if ($zeroCount > 0) {
                        $outputCharacters .= $digits[0];
                    }
                    $zeroCount = 0;
                    $outputCharacters .= $digits[$d] . $radices[$modulus];
                }
                if ($modulus == 0 && $zeroCount < 4) {
                    $outputCharacters .= $bigRadices[$quotient];
                }
            }
            $outputCharacters .= $CN_DOLLAR;
        }
        // 处理小数
        if ($decimal != "") {
            $floatlong = strlen($decimal);
            for ($i = 0; $i < $floatlong; $i++) {
                $d = substr($decimal,$i, 1);
                $ds = substr($decimal,-1, 1);
                if($d==0){
                    if($ds==0){
                        $outputCharacters .= "";
                    } else{
                        $outputCharacters .= $digits[$d];
                    }
                } else{
                    $outputCharacters .= $digits[$d] . $decimals[$i];
                }
            }
        }
        // 拼接转换后的字符串
        if ($outputCharacters == "") {
            $outputCharacters = $CN_ZERO . $CN_DOLLAR;
        }
        if ($decimal == "") {
            $outputCharacters .= $CN_INTEGER;
        }
        $outputCharacters = $CN_SYMBOL . $outputCharacters;
        return $outputCharacters;
    }

之前我发过一次这条博客,但是上次的方法有很严重的问题,即如果数字之间有0分隔,只会转化最后的0后边的数字,这次这个方法我已经尝试过了,没有发现什么问题,虽说不是原创,但是转化还是挺麻烦的,如果有帮到你,麻烦点个推荐吧

posted @ 2019-08-07 16:34  一剑还  阅读(740)  评论(0编辑  收藏  举报