Home > Backend Development > PHP Tutorial > How to format numbers with commas in php (code example)

How to format numbers with commas in php (code example)

藏色散人
Release: 2023-04-08 12:04:01
forward
2360 people have browsed it

How to format numbers with commas in php (code example)

Today’s work requires formatting numbers to display the current commodity price, such as 2335.32, which needs to be formatted as 2,335.32 to display like this. I wrote a function. I always feel that such a simple function requires more than 30 lines of code to complete.

The specific code is as follows:

<?php
/****
 * @author Amos Wang
 * @param $number
 * @return mixed
 */
function numberFormat($number)
{
    if(!is_numeric($number)){
        return $number;     //  只处理数字
    }
    list($integer,$decimal) = explode(&#39;.&#39;,$number);
    $number_temp = "";  //  临时计数
    $len = strlen($integer);
    $sublen = 3;    //  每隔几位数加逗号
    //处理整数部分
    $i=1;
   while(true){
       $pos = $i * $sublen;
       $join = empty($number_temp) ? "" : ","; // 连接符
       $number_temp = substr($integer,(0-$pos),$sublen).$join.$number_temp;
       if(($pos + $sublen) > $len){
           $number_temp = substr($integer,0,($len - $pos)).$join.$number_temp;
           break;
       }
       $i++;
   }
    //处理小数部分
    if(!empty($decimal)){
        $number_temp = !empty($number_temp) ? $number_temp.".".$decimal : "0.".$decimal;
    }
    return $number_temp;
}
$result = numberFormat(1234567.5564);
print_r($result);
?>
//结果输出1,234,567.5564
Copy after login

For more PHP related knowledge, please visit php tutorial!

The above is the detailed content of How to format numbers with commas in php (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:cnblogs.com
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