萬盛學電腦網

 萬盛學電腦網 >> 網絡編程 >> php編程 >> php 數字轉換成中文數字教程

php 數字轉換成中文數字教程

php 數字轉換成中文數字教程

class ChineseNumber
{
var $basical=array(0=>"零","一","二","三","四","五","六","七","八","九");
//var $basical=array(0=>"零","壹","貳","三","肆","伍","陸","柒","捌","玖");
var $advanced=array(1=>"十","百","千");
//var $advanced=array(1=>"拾","佰","仟");
var $top=array(1=>"萬","億");

var $level; // 以4位為一級

// 先實現萬一下的數的轉換
function ParseNumber($number)
{
if ($number>999999999999) // 只能處理到千億。
return "數字太大,無法處理。抱歉!";
if ($number==0)
return "零";

for($this->level=0;$number>0.0001;$this->level++,$number=floor($number / 10000))
{
// 對於中文來說,應該是4位為一組。
// 四個變量分別對應 個、十、百、千 位。
$n1=substr($number,-1,1);
if($number>9)
$n2=substr($number,-2,1);
else
$n2=0;
if($number>99)
$n3=substr($number,-3,1);
else
$n3=0;
if($number>999)
$n4=substr($number,-4,1);
else
$n4=0;

if($n4)
$parsed[$this->level].=$this->basical[$n4].$this->advanced[3];
else
if(($number/10000)>=1) // 千位為0,數值大於9999的情況
$parsed[$this->level].="零";
if($n3)
$parsed[$this->level].=$this->basical[$n3].$this->advanced[2];
else
if(!ereg("零$",$parsed[$this->level]) && ($number / 1000)>=1) // 不出現連續兩個“零”的情況
$parsed[$this->level].="零";
if($n2)
$parsed[$this->level].=$this->basical[$n2].$this->advanced[1];
else
if(!ereg("零$",$parsed[$this->level]) && ($number / 100)>=1) // 不出現連續兩個“零”的情況
$parsed[$this->level].="零";
if($n1)
$parsed[$this->level].=$this->basical[$n1];
}
for($this->level-=1;$this->level>=0;$this->level--)
{
$result.=$parsed[$this->level].$this->top[$this->level];
}

if(ereg("零$",$result))
$result=substr($result,0,strlen($result)-2);

return $result;

}
};

$c=new ChineseNumber();
echo $c->ParseNumber(123456789012);

copyright © 萬盛學電腦網 all rights reserved