PHP number three-bit comma-plus functional function _php tips

Source: Internet
Author: User
Tags explode float number

PHP implementation of the number format, the number of three-bit comma function function, the specific code is as follows:

function Num_format ($num) { 
 if (!is_numeric ($num)) {return 
  false; 
 } 
 $num = Explode ('. ', $num);/to separate integers and decimals 
 $rl = $num [1];//Fractional part value 
 $j = strlen ($num [0])% 3;//integer number 
 $SL = substr ($ Num[0], 0, $j)//Before the number of three digits out 
 $SR = substr ($num [0], $j), and/or after three-digit number 
 $i = 0; 
 while ($i <= strlen ($SR)) { 
  $rvalue = $rvalue. ', '. substr ($SR, $i, 3);//three-bit three-bit removed and merged, separated by commas 
  $i = $i + 3; 
 } 
 $rvalue = $sl. $rvalue; 
 $rvalue = substr ($rvalue, 0,strlen ($rvalue)-1)//Remove the last comma 
 $rvalue = explode (', ', $rvalue);//decompose the array of 
 if ($ rvalue[0]==0) { 
  array_shift ($rvalue);//If the first element is 0, delete the first element 
 } 
 $rv = $rvalue [the number of less than three digits in front of 0];//= for 
 ($i = 1; $i < count ($rvalue); $i + +) { 
  $rv = $rv. ', '. $rvalue [$i]; 
 } 
 if (!empty ($RL)) { 
  $rvalue = $rv. '. ' $RL//decimal is not null, integer and decimal merge 
 }else{ 
  $rvalue = $RV;//Decimal is empty, only integer 
 } return 
 $rvalue; 

You can also use the system's self-contained function string Number_format (float number [, int decimals [, String Dec_point, String thousands_sep]]):

Example:

 
 

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 implementation of the number of every three comma code, just beginning to see the topic is not no ideas, small series is also, hope that through this article can give you some inspiration.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.