Home  >  Article  >  Backend Development  >  PHP function to add comma to every three digits of numbers, PHP three-digit comma function_PHP tutorial

PHP function to add comma to every three digits of numbers, PHP three-digit comma function_PHP tutorial

WBOY
WBOYOriginal
2016-07-12 09:06:421089browse

php function to add commas to every three digits of numbers, php three-digit comma function

php implements number formatting, function to add commas to every three digits of numbers, the specific code is as follows :

function num_format($num){ 
 if(!is_numeric($num)){ 
  return false; 
 } 
 $num = explode('.',$num);//把整数和小数分开 
 $rl = $num[1];//小数部分的值 
 $j = strlen($num[0]) % 3;//整数有多少位 
 $sl = substr($num[0], 0, $j);//前面不满三位的数取出来 
 $sr = substr($num[0], $j);//后面的满三位的数取出来 
 $i = 0; 
 while($i <= strlen($sr)){ 
  $rvalue = $rvalue.','.substr($sr, $i, 3);//三位三位取出再合并,按逗号隔开 
  $i = $i + 3; 
 } 
 $rvalue = $sl.$rvalue; 
 $rvalue = substr($rvalue,0,strlen($rvalue)-1);//去掉最后一个逗号 
 $rvalue = explode(',',$rvalue);//分解成数组 
 if($rvalue[0]==0){ 
  array_shift($rvalue);//如果第一个元素为0,删除第一个元素 
 } 
 $rv = $rvalue[0];//前面不满三位的数 
 for($i = 1; $i < count($rvalue); $i++){ 
  $rv = $rv.','.$rvalue[$i]; 
 } 
 if(!empty($rl)){ 
  $rvalue = $rv.'.'.$rl;//小数不为空,整数和小数合并 
 }else{ 
  $rvalue = $rv;//小数为空,只有整数 
 } 
 return $rvalue; 
} 

In addition, you can use the system's own function string number_format ( float number [, int decimals [, string dec_point, string thousands_sep]] ):

Example:

echo number_format('169856420'); 

The output will be: 169,856,420

echo number_format('1000000',2); 

The output will be: 1,000,000.00

echo number_format('1000000',2,',','.'); 

The output will be: 1.000.000,00

The above is the PHP code to add commas to every three digits of a number. At first, when you saw the question, you may have no idea, and so did the editor. I hope this article can give you some inspiration.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/1063902.htmlTechArticlephp function to add comma to every three digits of numbers, php three digit comma function php implements number formatting, every number Function function with three digits plus comma, the specific code is as follows: function num_format($n...
Statement:
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