有時候寫會計系統,或者產出收據的時候,需要大寫的數字,以下就提供一個函數,幫你把數字轉換成國字

程式碼
	<?php
	function num2str($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." = ".num2str($a)."\n";
	echo $b." = ".num2str($b)."\n";
	echo $c." = ".num2str($c)."\n";
	?>
	
執行結果
	123456789 = 壹億貳仟參佰肆拾伍萬陸仟柒佰捌拾玖元整
	123456 = 壹拾貳萬參仟肆佰伍拾陸元整
	1500 = 壹仟伍佰元整
	

酷米 © All Rights Reserved.

loading
Loading...