網頁

2014年4月29日

[php] 金額數字轉換中文大寫數字

程式範例:
<?php
echo spellnumber(10120013201);


function spellnumber($money){
 //數字大寫
 $unt_th = array("", "拾", "佰", "仟");
 $unt_te = array("元整", "萬", "億", "兆", "京");
 $money_ch = array("零", "壹", "貳", "參", "肆", "伍", "陸", "柒", "捌", "玖");

 //將數字拆開
 $money = str_split($money);
 krsort($money);

 //每4位數拆成一個陣列
 $money = array_chunk($money, 4);

 $level = 0;
 foreach ($money as $num){
  krsort($num);
  $dec = 0;
  $num = implode("", $num);
  $zero = "";
  $mast = $num;
  $flag = false;

  while($num > 0){
   //十進位計算,取餘數
   $mod = $num % 10;
   if($mod > 0){
    $flag = true;
    //大寫數字 + 單位 + 零值
    $zero = $money_ch[$mod] . $unt_th[$dec] . $zero ;
   }else if ($mod == 0){
    //處理「零」的顯示
    if ($flag && ($level <= 1 || ($num && $mast%10 > 0))){
     $zero = "0" . $zero;
    }else{
     $zero = "" ;
    }
   }

   $num = intval($num / 10);
   $dec += 1; //進位
   $big_number[$level] = $zero.$unt_te[$level];
  }
  $level += 1;
 }
 krsort($big_number);
 $big_numbering = implode("", $big_number);

 return preg_replace('/0+/','零',$big_numbering); //中間連接多個0時,就直接顯示一個零

}
?>

輸出結果:
壹佰零壹億貳仟零壹萬參仟貳佰零壹元整