阿拉伯数字转中文数字(使用PHP实现)
<?php
//阿拉伯数字转中文数字
function numberToChinese(int $num)
{
//节权位的位置
$unit_section_pos = 0;
$chn_str = '';
//单个数字转换用的数组
$chn_num_char = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
//节权位转换用的数组
$chn_unit_section = ["", "万", "亿", "万亿", "亿亿"];
//节内权位换算的数组
$chn_unit_char = ["", "十", "百", "千"];
$need_zero = false;
if ($num === 0) {
return $chn_num_char[0];
}
//节内换算的闭包
$section_to_chinese = function ($section) use ($chn_num_char, $chn_unit_char) {
$chn_str = '';
//节内的位置
$unit_pos = 0;
$zero = true;
while ($section > 0) {
$v = $section % 10;
if ($v === 0) {
if (!$zero) {
$zero = true;
$chn_str = $chn_num_char[$v] . $chn_str;
}
} else {
$zero = false;
$str_ins = $chn_num_char[$v];
$str_ins .= $chn_unit_char[$unit_pos];
$chn_str = $str_ins . $chn_str;
}
$unit_pos++;
$section = floor($section / 10);
}
return $chn_str;
};
while ($num > 0) {
$section = $num % 10000;
if ($need_zero) {
$chn_str = $chn_num_char[0] . $chn_str;
}
$str_ins = $section_to_chinese($section);
$str_ins .= ($section !== 0) ? $chn_unit_section[$unit_section_pos] : $chn_unit_section[0];
$chn_str = $str_ins . $chn_str;
$need_zero = ($section < 1000) && ($section > 0);
$num = floor($num / 10000);
$unit_section_pos++;
}
$search = '一十';
$replacement = '十';
//处理含一十开头的(这个可根据需求处理)
if (mb_substr($chn_str, 0, 2) === $search) {
$position = strpos($chn_str, $search);
$chn_str = substr_replace($chn_str, $replacement, $position, strlen($search));
}
return $chn_str;
}
echo numberToChinese(1000001);