今天需要把数值人民币转换成大写的人民币,用GPT一问,结果各种有问题,在网上也找了很多,也是运行某些数值的时候有问题,最后找到了一个好用的,稍微改造一下就实现了。
<?php function Chinese_RMB($num) { $rmbNum = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖']; $rmbUnit = ['分', '角', '元', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿', '拾', '佰', '仟', '万', '拾', '佰', '仟']; //数字预处理 $num = number_format($num, 2, '.', '') * 100; if (strlen(number_format($num, 0, '', '')) > 18) { return '输入的金额不得超过千万亿!'; } //开始数字转换人民币大写 $rmb = ''; for ($out1 = 0; $out1 < strlen(number_format($num, 0, '', '')); $out1++) { $numRmb = $rmbNum[substr(number_format($num, 0, '', ''), $out1, 1)]; $unit = $rmbUnit[strlen(number_format($num, 0, '', '')) - $out1 - 1]; $rmb = $rmb . $numRmb . $unit; } // 将大写人民币中的零进行调整 $rmbStrlen = strlen($rmb); for ($out2 = 0; $out2 < $rmbStrlen; $out2 = $out2 + 3) { $tempRmb = substr($rmb, $out2, 6); if ($tempRmb == '零元' || $tempRmb == '零万' || $tempRmb == '零亿') { $left = substr($rmb, 0, $out2); $right = substr($rmb, $out2 + 3); $rmb = $left . $right; $out2 = $out2 - 3; $rmbStrlen = $rmbStrlen - 3; } elseif ($tempRmb == '零拾' || $tempRmb == '零佰' || $tempRmb == '零仟') { $left = substr($rmb, 0, $out2 + 3); $right = substr($rmb, $out2 + 6); $rmb = $left . $right; $out2 = $out2 - 3; $rmbStrlen = $rmbStrlen - 3; } elseif ($tempRmb == '零分' || $tempRmb == '零角') { $left = substr($rmb, 0, $out2); $right = substr($rmb, $out2 + 6); $rmb = $left . $right; $out2 = $out2 - 6; $rmbStrlen = $rmbStrlen - 6; } if ($tempRmb == '零零') { $left = substr($rmb, 0, $out2); $right = substr($rmb, $out2 + 3); $rmb = $left . $right; $out2 = $out2 - 3; $rmbStrlen = $rmbStrlen - 3; } if (substr($rmb, strlen($rmb) - 3) == '元') { $rmb = $rmb . '整'; } } return $rmb; } // 调用函数 echo $num = "10101564.23"; echo "<br />"; echo Chinese_RMB($num); ?>
输出:
// 调用函数 echo $num = "100730213.56"; echo "<br />"; echo Chinese_RMB($num);
壹亿零柒拾叁万零贰佰壹拾叁元伍角陆分