PHP阿拉伯数字转中文汉字(改造)

/**
     * 数字格式化成汉字
     * 
     * @param number $figure 待格式化的数字
     * @param boolean $capital 使用汉字大写数字
     * @param boolean $mode 单字符转换模式
     * @return string
     */
    public static function toChineseNumerals($figure, $capital = false, $mode = true) {

        $numberChar = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
        $unitChar = ['', '十', '百', '千', '', '万', '亿', '兆', '京', '垓', '秭', '穣', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祇', '那由他', '不可思议', '无量大数'];
        if ($capital !== false) {
            $numberChar = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
            $unitChar = ['', '拾', '佰', '仟', '', '万', '亿', '兆', '京', '垓', '秭', '穣', '沟', '涧', '正', '载', '极', '恒河沙', '阿僧祇', '那由他', '不可思议', '无量大数'];
        }



        $dec = "点";
        $target = '';
        $matches = [];

        if ($mode) {
            preg_match("/^0*(\d*)\.?(\d*)/", $figure, $matches);
        } else {
            preg_match("/(\d*)\.?(\d*)/", $figure, $matches);
        }

        list(, $number, $point) = $matches;

        if ($point) {
            $target = $dec . self::toChineseNumerals($point, $capital, false);
        }

        if (!$number) {
            return $target;
        }

        $str = strrev($number);
        for ($i = 0; $i < strlen($str); $i++) {
            $out[$i] = $numberChar[$str[$i]];
            if ($mode === false) {
                continue;
            }
            $out[$i] .= $str[$i] != '0' ? $unitChar[$i % 4] : '';
            if ($i > 0 && $str[$i] + $str[$i - 1] == 0) {
                $out[$i] = '';
            }
            if ($i % 4 == 0) {
                $temp = substr($str, $i, 4);
                $out[$i] = str_replace($numberChar[0], '', $out[$i]);
                if (strrev($temp) > 0) {
                    $out[$i] .= $unitChar[4 + floor($i / 4)];
                } else {
                    $out[$i] .= $numberChar[0];
                }
            }
        }
        return join('', array_reverse($out)) . $target;
    }

相关来源作者思路优化: https://blog.csdn.net/betterman_1/article/details/77646429

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值