一些比較正式的系統,對於數字很敏感,除了要有逗號(使用內建number_format函數)分隔格式之外,需要大寫國字,比如說10000,需要寫成10,000,或者寫成壹萬,尤其在會計帳務、請款單、收據、發票、報表...,很多地方都會要求有這樣功能,以下我們就來教學一下,PHP到底怎麼實現呢?

undefined

程式碼如下:

<?php
function num2cht($num){
	$numc ="零,壹,貳,參,肆,伍,陸,柒,捌,玖";
	$unic = ",拾,佰,仟";
	$unic1 = "元整,萬,億,兆,京";
	$numc_arr = split(",", $numc);
	$unic_arr = split(",", $unic);
	$unic1_arr = split(",", $unic1);
	$i = str_replace(",", "", $num);
	$c0 = 0;
	$str = array();
	do{
		$aa = 0;
		$c1 = 0;
		$s = "";
		$lan = (strlen($i) >= 4) ? 4 : strlen($i);
		$j = substr($i, -$lan);
		while($j > 0){
			$k = $j % 10;
			if($k > 0) {
				$aa = 1;
				$s = $numc_arr[$k].$unic_arr[$c1].$s;
			}elseif($k == 0) {
				if($aa == 1) $s = "0".$s;
			}
			$j = intval($j / 10);
			$c1 += 1;
		}
		$str[$c0] = ($s == '') ? '' : $s.$unic1_arr[$c0];
		$count_len = strlen($i) - 4;
		$i = ($count_len > 0) ? substr($i, 0, $count_len) : '';
		$c0 += 1;
	}while($i != '');
	foreach($str as $v) $string .= array_pop($str);
	$string = preg_replace('/0+/', '零', $string);
	return $string;
}
?>

使用方法:

<?php
$a = 123456789;
$b = 123456;
$c = 1500;
echo $a." = ".num2cht($a)."\n";
echo $b." = ".num2cht($b)."\n";
echo $c." = ".num2cht($c)."\n";
?>

執行結果:

123456789 = 壹億貳仟參佰肆拾伍萬陸仟柒佰捌拾玖元整
123456 = 壹拾貳萬參仟肆佰伍拾陸元整
1500 = 壹仟伍佰元整

 

 

 

 

 

 

arrow
arrow

    HC 發表在 痞客邦 留言(0) 人氣()