php 金额格式胡

发布时间 2023-10-27 10:55:56作者: 萌妹子的vlog
//转换不彻底
function ExchangeMoney($N_money){
$A_tmp=explode(".",$N_money ); //将数字按小数点分成两部分,并存入数组$A_tmp
$I_len=strlen($A_tmp[0]); //测出小数点前面位数的宽度
if($I_len%3==0) {
$I_step=$I_len/3; //如前面位数的宽度mod 3 = 0 ,可按,分成$I_step 部分
}else {
$step=($I_len-$I_len%3)/3+1; //如前面位数的宽度mod 3 != 0 ,可按,分成$I_step 部分+1
}
$C_cur="";
//对小数点以前的金额数字进行转换
while($I_len<>0) {
$I_step--;
if($I_step==0) {
$C_cur .= substr($A_tmp[0],0,$I_len-($I_step)*3);
}else {
$C_cur .= substr($A_tmp[0],0,$I_len-($I_step)*3).",";
}
$A_tmp[0]=substr($A_tmp[0],$I_len-($I_step)*3);
$I_len=strlen($A_tmp[0]);
}
//对小数点后面的金额的进行转换
if($A_tmp[1]=="") {
$C_cur .= ".00";
}else {
$I_len=strlen($A_tmp[1]);
if($I_len<2) {
$C_cur .= ".".$A_tmp[1]."0";
}else {
$C_cur .= ".".substr($A_tmp[1],0,2);
}
}
return $C_cur;
}
//转换彻底,但是小数点如果只有一位,不补零待改进
function ExchangeMoney($money, $digit = 3, $separator = ','){
$sm = (string)abs($money);
$dot = strstr($sm, '.');
if ($dot) {
$sm = strstr($sm, '.', true);
}
$s = strlen($sm) % $digit; // 开始下标
$num = (strlen($sm) - $s) / $digit; // 次数

for ($i = 0; $i < $num; $i++) {
if ($i != 0) {
$s += $digit;
} else {
if ($s == 0) {
continue;
}
}
$sm = substr_replace($sm, $separator, $s, 0);
$s++;
}

if ($money < 0) {
$sm = '-' . $sm;
}
return $sm . $dot;
}