Home > Article > Backend Development > PHP comes with a function to add 0 or digits before numbers.
This article mainly introduces PHP's own function to add 0 or pad before numbers. It has a certain reference value. Now I share it with you. Friends in need can refer to it
Many times we need Format the number, for example, if there are insufficient digits, add 0 in front of it. It can be easily implemented with PHP, because PHP comes with related functions.
<?php //生成4位数,不足前面补0 $var=sprintf("%04d", 2); echo $var;//结果为0002 echo date('Y_m_d', time()).'_'.sprintf('d', rand(0,99)); ?>
sprintf() function
Does it feel like C language
1. Syntax
sprintf(format,arg1,arg2,arg++)
Parameters | Description |
---|---|
format | Required. Convert format. |
arg1 | Required. Specifies the parameters to be inserted at the first % sign in the format string. |
arg2 | Optional. Specifies the parameter to be inserted into the format string at the second % sign. |
arg | Optional. Specifies the parameters to be inserted into the format string at the third, fourth, etc. % symbols. |
#2. Description
The parameter format is the conversion format, starting with the percent sign ("%") and ending with the conversion character. The following possible format values:
%% - returns the percent symbol
%b - the binary number
%c - Character according to ASCII value
%d - Signed decimal number
%e - Continuous notation (For example, 1.5e 3)
<?php $number = 123; $txt = sprintf("%f",$number); echo $txt; ?>3. Format number number_format()
<?php $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 ?>Related recommendations:
Complete PHP built-in functions_PHP tutorial
Simple shopping cart function in php’s built-in function
##
The above is the detailed content of PHP comes with a function to add 0 or digits before numbers.. For more information, please follow other related articles on the PHP Chinese website!