Home > php教程 > PHP源码 > PHP实现数字格式化,每三位加逗号

PHP实现数字格式化,每三位加逗号

PHP中文网
Release: 2016-05-25 17:05:50
Original
1181 people have browsed it

PHP实现数字格式化,每三位加逗号

<?php
function num_format($num){
if(!is_numeric($num)){
return false;
}
$rvalue=&#39;&#39;;
$num = explode(&#39;.&#39;,$num);//把整数和小数分开
$rl = !isset($num[&#39;1&#39;]) ? &#39;&#39; : $num[&#39;1&#39;];//小数部分的值
$j = strlen($num[0]) % 3;//整数有多少位
$sl = substr($num[0], 0, $j);//前面不满三位的数取出来
$sr = substr($num[0], $j);//后面的满三位的数取出来
$i = 0;
while($i <= strlen($sr)){
$rvalue = $rvalue.&#39;,&#39;.substr($sr, $i, 3);//三位三位取出再合并,按逗号隔开
$i = $i + 3;
}
$rvalue = $sl.$rvalue;
$rvalue = substr($rvalue,0,strlen($rvalue)-1);//去掉最后一个逗号
$rvalue = explode(&#39;,&#39;,$rvalue);//分解成数组
if($rvalue[0]==0){
array_shift($rvalue);//如果第一个元素为0,删除第一个元素
}
$rv = $rvalue[0];//前面不满三位的数
for($i = 1; $i < count($rvalue); $i++){
$rv = $rv.&#39;,&#39;.$rvalue[$i];
}
if(!empty($rl)){
$rvalue = $rv.&#39;.&#39;.$rl;//小数不为空,整数和小数合并
}else{
$rvalue = $rv;//小数为空,只有整数
}
return $rvalue;
}
Copy after login
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template