萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 數字轉中文大寫/小寫完整實作:支援萬億級、金融格式與自定義單位

需求場景

  • 財務系統:金額轉中文大寫 (壹貳參...)
  • 合約列印:數字轉中文小寫 (一二三...)
  • 中文排版:數字轉漢字易讀性更好

完整類別實作

class ChineseNumber {
    // 基礎數字:可切換大小寫
    private $basic = [
        0 => '零', '一', '二', '三', '四', '五', '六', '七', '八', '九'
    ];
    // 金融大寫對照
    private $financial = [
        0 => '零', '壹', '貳', '參', '肆', '伍', '陸', '柒', '捌', '玖'
    ];
    
    // 位權單位:十、百、千
    private $units = [1 => '十', '百', '千'];
    private $finUnits = [1 => '拾', '佰', '仟'];
    
    // 高階單位:萬、億、兆...
    private $highUnits = [1 => '萬', '億', '兆', '京'];
    
    private $useFinancial = false;
    
    public function __construct(bool $financial = false) {
        $this->useFinancial = $financial;
    }
    
    public function convert(int|float|string $number): string {
        // 處理負數
        $negative = false;
        if (is_string($number)) {
            $number = trim($number);
            if (str_starts_with($number, '-')) {
                $negative = true;
                $number = substr($number, 1);
            }
        } elseif ($number < 0) {
            $negative = true;
            $number = -$number;
        }
        
        // 處理小數 (金額角分)
        $decimal = '';
        if (str_contains((string)$number, '.')) {
            [$intPart, $decPart] = explode('.', (string)$number);
            $number = (int)$intPart;
            // 只取前兩位 (角、分)
            $decPart = substr($decPart . '00', 0, 2);
            if ($decPart != '00') {
                $decimal = $this->convertDecimal($decPart);
            }
        }
        
        if ($number == 0) {
            return $negative ? '負零' . $decimal : '零' . $decimal;
        }
        
        $result = $this->convertInteger((int)$number);
        return ($negative ? '負' : '') . $result . $decimal;
    }
    
    private function convertInteger(int $num): string {
        if ($num == 0) return '';
        
        $basic = $this->useFinancial ? $this->financial : $this->basic;
        $units = $this->useFinancial ? $this->finUnits : $this->units;
        
        $segments = [];
        $level = 0;
        
        while ($num > 0) {
            $segment = $num % 10000; // 以 4 位為一段 (萬進制)
            $num = (int)($num / 10000);
            
            if ($segment > 0) {
                $segStr = $this->convertSegment($segment, $basic, $units);
                if ($level > 0) {
                    $segStr .= $this->highUnits[$level];
                }
                $segments[] = $segStr;
            } elseif (!empty($segments)) {
                // 處理中間段為 0 的情況 (如 10001 -> 一萬零一)
                $segments[] = '零';
            }
            $level++;
        }
        
        // 反轉並合併,處理連續零
        $result = implode('', array_reverse($segments));
        return preg_replace('/零+/', '零', $result); // 合併連續零
    }
    
    private function convertSegment(int $num, array $basic, array $units): string {
        if ($num == 0) return '';
        
        $digits = [
            $num % 10,           // 個位
            ($num / 10) % 10,    // 十位
            ($num / 100) % 10,   // 百位
            ($num / 1000) % 10,  // 千位
        ];
        
        $str = '';
        for ($i = 3; $i >= 0; $i--) {
            $d = $digits[$i];
            if ($d > 0) {
                // 處理十位特殊情況:十、二十、三十... (中文習慣不說「一十」)
                if ($i == 1 && $d == 1 && $num < 20) {
                    $str .= $units[1]; // 只輸出「十」
                } else {
                    $str .= $basic[$d] . ($i > 0 ? $units[$i] : '');
                }
            } elseif (!empty($str) && !preg_match('/零$/', $str)) {
                // 避免連續零,且不在字串開頭加零
                $str .= '零';
            }
        }
        
        return rtrim($str, '零'); // 移除尾端零
    }
    
    private function convertDecimal(string $twoDigits): string {
        $basic = $this->useFinancial ? $this->financial : $this->basic;
        $jiao = (int)$twoDigits[0];
        $fen  = (int)$twoDigits[1];
        
        $str = '';
        if ($jiao > 0) $str .= $basic[$jiao] . '角';
        if ($fen > 0)  $str .= $basic[$fen] . '分';
        if ($jiao == 0 && $fen > 0) $str = '零' . $str; // 如 0.05 -> 零角五分
        
        return $str;
    }
}

// 使用範例
$c = new ChineseNumber();
echo $c->convert(123456789012);       // 一千二百三十四億五千六百七十八萬九千零一十二
$c2 = new ChineseNumber(true);
echo $c2->convert('12345.67');        // 壹萬貳仟參佰肆拾伍元陸角柒分
echo $c->convert(-10086);             // 負一萬零八十六

關鍵設計點解析

  1. 四位一段 (萬進制):符合中文閱讀習慣,萬、億、兆每 4 位進位
  2. 零的處理:段內不連續零、段間單一零、尾端不留零
  3. 十位特例:11-19 習慣說「十一」而非「一十一」
  4. 金融大寫:防竄改必備,支援元/角/分單位
  5. 型別彈性:支援 int、float、string 輸入,避免大數精度損失

擴展建議

  • 支援小數點後任意位數 (科學計算)
  • 支援分數、百分比格式
  • 加入緩存機制 (大量轉換時)
  • 單元測試覆蓋邊界值:0、負數、純小數、大數、連續零
copyright © 萬盛學電腦網 all rights reserved