数字金额转汉字金额
// 测试
public function testNum() {
$money = 40000000.01;
$money = 1000000000.01;
$res = $this->numToRmb($money);
dump($res);
}
/**
* 数字金额转汉字金额
*
* @param float $money 数字金额
* @param int $type 已弃用
* @return string 汉字金额
*/
public function numToRmb($money, $type = 0){
if (empty($money)) {
return '零';
}
$money = round($money,2); //只保留两位有效数字
dump($money);
list($int,$dec) = explode(".",$money,2);
$cnyNums = ['零', '壹' ,'贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
$cnyGre = ['拾', '佰' ,'仟','万','拾', '佰' ,'仟', '亿','拾', '佰' ,'仟'];
// 整数部分操作
$str = ''; //返回的字符串
$isT = false; // 是否已经填过一次'零'
$len = strlen($int) - 1;
$i = $len;
while ($i >= 0) {
if ($int[$len - $i] == 0 ) {
if (!$isT) {
$isT = true;
$str .= $cnyNums[$int[$len - $i]];
}
// 保存 万、亿等单位
if ($i % 4 == 0 && $i > 0){
if (mb_substr($str, -1, 1) == '零') {
$str = mb_substr($str,0, mb_strlen($str) - 1);
}
if (mb_substr($str, -1, 1) != '亿') {
$str .= $cnyGre[$i - 1];
}
$isT = false;
}
} else {
$isT = false;
$str .= $cnyNums[$int[$len - $i]];
if ($i > 0 ){
$str .= $cnyGre[$i - 1];
}
}
--$i;
}
// 如果汉字金额末尾包含 零, 则删除
if (mb_substr($str, -1, 1) == '零') {
$str = mb_substr($str,0, mb_strlen($str) - 1);
}
$isExistInt = true; // 是否存在整数部分
if (empty($str)) {
$isExistInt = false;
}
$str .= $this->numToRmbDec($dec, $isExistInt, $type);
return $str;
}
/**
* 数字金额转汉字金额
* 小数部分
* @param float $dec 小数金额
* @param bool $isExistInt true 存在整数部分 false 不存在
* @param int $type 已弃用
* @return string 汉字金额
*/
public function numToRmbDec($dec, $isExistInt, $type = 0)
{
$cnyNums = ['零', '壹' ,'贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
if (empty($dec) || ($dec[0] == 0 && empty($dec[1]))) {
return '圆整';
}
$str = $isExistInt == true ? '圆' : '';
$str .= $cnyNums[$dec[0]];
if ($dec[0] != 0) {
$str .= '角';
}
if (empty($dec[1])) {
return $str;
}
$str .= $cnyNums[$dec[1]] . '分';
return $str;
}