Home > Backend Development > PHP Tutorial > PHP implements number formatting, a function that adds commas to every three digits of a number

PHP implements number formatting, a function that adds commas to every three digits of a number

墨辰丷
Release: 2023-03-30 10:16:02
Original
2776 people have browsed it

This article mainly introduces PHP to implement number formatting and the function of adding commas to every three digits of numbers. Interested friends can refer to it. I hope it will be helpful to everyone.

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.&#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

In addition, you can use the function that comes with the systemstring number_format (float number [, int decimals [, string dec_point, string thousands_sep]] ) :

Example:

echo number_format(&#39;169856420&#39;);
Copy after login

The output result will be:169,856,420

echo number_format(&#39;1000000&#39;,2);
Copy after login

The output result will be: 1,000,000.00

echo number_format(&#39;1000000&#39;,2,&#39;,&#39;,&#39;.&#39;);
Copy after login

The output result will be: 1.000.000,00

Summary: The above is the entire content of this article, I hope It can be helpful to everyone’s study.

Related recommendations:

Detailed examples of processing uploaded files in PHP

How to implement a simple probability in PHP

Methods and simple examples of while loop control in php

The above is the detailed content of PHP implements number formatting, a function that adds commas to every three digits of a number. For more information, please follow other related articles on the PHP Chinese website!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template