第一種
第二種
header("Content-Type:text/html;charset=utf-8");
function cny($ns) {
static $cnums=array("零","壹","貳","叁","肆","伍","陸","柒","捌","玖"),
$cnyunits=array("圓","角","分"),
$grees=array("拾","佰","仟","萬","拾","佰","仟","億");
list($ns1,$ns2)=explode(".",$ns,2);
$ns2=array_filter(array($ns2[1],$ns2[0]));
$ret=array_merge($ns2,array(implode("",_cny_map_unit(str_split($ns1),$grees)),""));
$ret=implode("",array_reverse(_cny_map_unit($ret,$cnyunits)));
return str_replace(array_keys($cnums),$cnums,$ret);
}
function _cny_map_unit($list,$units) {
$ul=count($units);
$xs=array();
foreach (array_reverse($list) as $x) {
$l=count($xs);
if ($x!="0" || !($l%4)) $n=($x=='0'?"":$x).($units[($l-1)%$ul]);
else $n=is_numeric($xs[0][0])?$x:"";
array_unshift($xs,$n);
}
return $xs;
}
echo @cny('150.25');//輸出結果為壹佰伍拾圓貳角伍分
第三種
function num2rmb($number = 0, $int_unit = '元', $is_round = TRUE, $is_extra_zero = FALSE)
{
// 将數字切分成兩段
$parts = explode('.', $number, 2);
$int = isset($parts[0]) ? strval($parts[0]) : '0';
$dec = isset($parts[1]) ? strval($parts[1]) : '';
// 如果小數點後多于2位,不四舍五入就直接截,否則就處理
$dec_len = strlen($dec);
if (isset($parts[1]) && $dec_len > 2)
{
$dec = $is_round
? substr(strrchr(strval(round(floatval("0.".$dec), 2)), '.'), 1)
: substr($parts[1], 0, 2);
}
// 當number為0.001時,小數點後的金額為0元
if(empty($int) && empty($dec))
{
return '零';
}
// 定義
$chs = array('0','壹','貳','叁','肆','伍','陸','柒','捌','玖');
$uni = array('','拾','佰','仟');
$dec_uni = array('角', '分');
$exp = array('', '萬');
$res = '';
// 整數部分從右向左找
for($i = strlen($int) - 1, $k = 0; $i >= 0; $k++)
{
$str = '';
// 按照中文讀寫習慣,每4個字為一段進行轉化,i一直在減
for($j = 0; $j < 4 && $i >= 0; $j++, $i--)
{
$u = $int{$i} > 0 ? $uni[$j] : ''; // 非0的數字後面添加機關
$str = $chs[$int{$i}] . $u . $str;
}
//echo $str."|".($k - 2)."
";
$str = rtrim($str, '0');// 去掉末尾的0
$str = preg_replace("/0+/", "零", $str); // 替換多個連續的0
if(!isset($exp[$k]))
{
$exp[$k] = $exp[$k - 2] . '億'; // 建構機關
}
$u2 = $str != '' ? $exp[$k] : '';
$res = $str . $u2 . $res;
}
// 如果小數部分處理完之後是00,需要處理下
$dec = rtrim($dec, '0');
// 小數部分從左向右找
if(!empty($dec))
{
$res .= $int_unit;
// 是否要在整數部分以0結尾的數字後附加0,有的系統有這要求
if ($is_extra_zero)
{
if (substr($int, -1) === '0')
{
$res.= '零';
}
}
for($i = 0, $cnt = strlen($dec); $i < $cnt; $i++)
{
$u = $dec{$i} > 0 ? $dec_uni[$i] : ''; // 非0的數字後面添加機關
$res .= $chs[$dec{$i}] . $u;
}
$res = rtrim($res, '0');// 去掉末尾的0
$res = preg_replace("/0+/", "零", $res); // 替換多個連續的0
}
else
{
$res .= $int_unit . '整';
}
return $res;
}
echo "
";
$number = "1000000000000000012345678900.501";
echo $number.":".num2rmb($number);
echo "\n";
$number = "1960.30";
echo $number.":".num2rmb($number);
echo "\n";
$number = "1960.30";
echo $number.":".num2rmb($number, "圓", true, true);
echo "\n";
$number = "123456789.005";
echo $number.":".num2rmb($number);
echo "\n";
$number = "123456789.005";
echo $number.":".num2rmb($number, "元", false);
echo "\n";
$number = "10000000000000000060009.101";
echo $number.":".num2rmb($number);
echo "\n";
$number = "1680.32";
echo $number.":".num2rmb($number);