Skip to content

Commit 831e7f8

Browse files
committed
修复公用函数返回编码问题(四无法输出)
1 parent 8e59804 commit 831e7f8

1 file changed

Lines changed: 40 additions & 29 deletions

File tree

app/helpers.php

Lines changed: 40 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,47 @@
11
<?php
22

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;
1932
}
20-
} else {
21-
$zeroFlag = false;
22-
$chars[] = $units[$i];
23-
$chars[] = $numbers[$n];
33+
$currentPart = intdiv($currentPart, 10);
34+
$digitIndex++;
2435
}
36+
$part = $tempPart . $bigNumbers[$partIndex];
37+
}
38+
if ($part != '') {
39+
array_unshift($parts, $part);
2540
}
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++;
3542
}
43+
44+
return $negative . implode('', $parts);
3645
}
46+
47+

0 commit comments

Comments
 (0)