PHP實現數字金額轉中文金額

 解決發票系統中,發票單上需要填寫中文金額的問題:

 function ToChineseNum($num) {
        $zh_num = ['零', '壹', '貳', '叄', '肆', '伍', '陸', '柒', '捌', '玖'];
        $zh_unit = ['分', '角', '元', '拾', '佰', '仟', '萬', '拾', '佰', '仟', '億', '拾', '佰', '仟'];
        if (!is_numeric(str_replace(',', '', $num))) {
            return $num;
        }
        $number = strrev(round(str_replace(',', '', $num), 2) * 100);
        $length = strlen($number);
        $ch_str = '';
        for ($length; $length > 0; $length--) {
            $index = $length - 1;
            if ($number[$index] == '0' && !in_array($zh_unit[$index], ['萬', '元', '億'])) {
                $ch_str.=$zh_num[$number[$index]];
            } elseif ($number[$index] == '0' && in_array($zh_unit[$index], ['萬', '元', '億'])) {
                $ch_str.= $zh_unit[$index];
            } else {
                $ch_str.=$zh_num[$number[$index]] . $zh_unit[$index];
            }
        }
        $format_str = trim(preg_replace(['/零{2,}/u', '/零萬/', '/零元/', '/零億/'], ['零', '萬', '元', '億'], $ch_str), '零');
        if (preg_match('/(分|角)/', $format_str) === 0) {
            $format_str.='整';
        }
        return $format_str;
    }


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章