|
1 | 1 | <?php |
2 | 2 |
|
3 | | -if (!function_exists('numberToChinese')) { |
4 | | - function numberToChinese($number) |
5 | | - { |
6 | | - $numbers = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']; |
7 | | - $units = ['', '十', '百', '千', '万', '十万', '百万', '千万', '亿']; |
8 | | - $chars = []; |
9 | | - $number = strval($number); // 确保 number 是字符串类型 |
10 | | - $length = strlen($number); |
11 | | - $zeroFlag = false; // 标记是否连续零 |
12 | | - |
13 | | - for ($i = 0; $i < $length; $i++) { |
14 | | - $n = $number[$length - $i - 1]; |
15 | | - if ($n == "0") { |
16 | | - if (!$zeroFlag) { |
17 | | - $chars[] = $numbers[$n]; |
18 | | - $zeroFlag = true; |
| 3 | +function numberToChinese($number) { |
| 4 | + $digits = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']; |
| 5 | + $tens = ['', '十', '百', '千']; |
| 6 | + $bigNumbers = ['', '万', '亿', '兆']; |
| 7 | + |
| 8 | + if ($number == 0) { |
| 9 | + return '零'; |
| 10 | + } |
| 11 | + |
| 12 | + $negative = $number < 0 ? '负' : ''; |
| 13 | + $number = abs($number); |
| 14 | + |
| 15 | + $parts = []; |
| 16 | + $partIndex = 0; |
| 17 | + |
| 18 | + while ($number > 0) { |
| 19 | + $part = ''; |
| 20 | + $currentPart = $number % 10000; |
| 21 | + $number = intdiv($number, 10000); |
| 22 | + |
| 23 | + if ($currentPart > 0) { |
| 24 | + $tempPart = ''; |
| 25 | + $digitIndex = 0; |
| 26 | + while ($currentPart > 0) { |
| 27 | + $digit = $currentPart % 10; |
| 28 | + if ($digit > 0) { |
| 29 | + $tempPart = $digits[$digit] . ($digitIndex > 0 ? $tens[$digitIndex] : '') . $tempPart; |
| 30 | + } else if (strlen($tempPart) > 0 && !str_ends_with($tempPart, '零')) { |
| 31 | + $tempPart = '零' . $tempPart; |
19 | 32 | } |
20 | | - } else { |
21 | | - $zeroFlag = false; |
22 | | - $chars[] = $units[$i]; |
23 | | - $chars[] = $numbers[$n]; |
| 33 | + $currentPart = intdiv($currentPart, 10); |
| 34 | + $digitIndex++; |
24 | 35 | } |
| 36 | + $part = $tempPart . $bigNumbers[$partIndex]; |
| 37 | + } |
| 38 | + if ($part != '') { |
| 39 | + array_unshift($parts, $part); |
25 | 40 | } |
26 | | - $chars = array_reverse($chars); |
27 | | - $chars = implode('', $chars); |
28 | | - $chars = preg_replace('/零[十百千]/u', '零', $chars); |
29 | | - $chars = preg_replace('/零+/u', '零', $chars); |
30 | | - $chars = rtrim($chars, '零'); |
31 | | - $chars = preg_replace('/零万/u', '万', $chars); |
32 | | - $chars = preg_replace('/零亿/u', '亿', $chars); |
33 | | - $chars = str_replace('一十', '十', $chars); |
34 | | - return $chars; |
| 41 | + $partIndex++; |
35 | 42 | } |
| 43 | + |
| 44 | + return $negative . implode('', $parts); |
36 | 45 | } |
| 46 | + |
| 47 | + |
0 commit comments