解決發票系統中,發票單上須要填寫中文金額的問題:
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; }