Home > Article > Backend Development > How to format numbers in php and add 0 in front of insufficient digits
PHP formats numbers. When there are insufficient digits, add 0 in front to make up for it. This article provides two implementation methods, using sprintf and number_format respectively. Friends in need, come and take a look.
Example of php formatting numbers. <?php $var=sprintf("%04d", 2);//生成4位数,不足前面补0 echo $var;//结果为0002 ?> 1. String sprintf() function Grammar sprintf(format,arg1,arg2,arg++)
The parameter format is the format of the conversion, starting with the percent sign ("%") and ending with the conversion character. The following possible format values are: %% - returns the percent symbol %b - binary number %c - character according to ASCII value %d - signed decimal number %e - Continuous counting method (e.g. 1.5e+3) %u - unsigned decimal number %f - floating point number (local settings aware) %F - floating point number (not local settings aware) %o - octal number %s - string %x - hexadecimal number (lowercase letters) %X - Hexadecimal number (capital letters) arg1, arg2, ++, etc. are inserted into the main string at the percent sign (%) symbol. This function is executed step by step. At the first % sign, arg1 is inserted, at the second % sign, arg2, and so on. Example: <?php $number = 123; $txt = sprintf("%f",$number); echo $txt; ?> 2. Format number function number_format() Example: <?php //number_format 格式化数字 $number = 1234.56; // english notation (default) $english_format_number = number_format($number); // 1,235 // French notation $nombre_format_francais = number_format($number, 2, ',', ' '); // 1 234,56 $number = 1234.5678; // english notation without thousands seperator $english_format_number = number_format($number, 2, '.', ''); // 1234.57 //by http://bbs.it-home.org ?> |