PHP comes with a function to automatically fill in the number of digits for a number or string

  • 2021-07-10 18:59:36
  • OfStack

Let's take a look at an example first: the requirement is to generate 4 digits, and make up 0 before it is insufficient


<?php  
// Generate 4 Number of digits, make up for it before it is insufficient 0  
$var=sprintf("%04d", 2);
echo $var;// The result is 0002  
echo date('Y_m_d', time()).'_'.sprintf('d', rand(0,99));
?>

sprintf () function

Does it feel like c language

1. Grammar

sprintf(format,arg1,arg2,arg++)
Parameter description
format Required. Convert the format.
arg1 required. Specifies the parameter inserted at the first% sign in the format string.
arg2 is optional. Specifies the parameter inserted at the second% symbol in the format string.
arg + + is optional. Specifies the parameters inserted in the format string at the 3. 4 and so on% symbol.

Step 2: Description

The parameter format is the format of the conversion, starting with the percentage sign ("%") and ending with the conversion character. The following possible format values:

%%-Returns a percentage symbol
% b-binary number
% c-Characters according to ASCII value
% d-signed decimal number
% e-Continuous Enumeration (e.g. 1.5 e+3)
% u-unsigned decimal number
% f-Floating point numbers (local settings aware)
% F-Floating Point Number (not local settings aware)
% o-8 digits
% s-String
% x-106 binary numbers (lowercase letters)
% X-106 binary numbers (uppercase letters)
Parameters such as arg1, arg2, + + are inserted into the main string at the percent sign (%) symbol. This function is executed step by step. In the first% sign, insert arg1, in the second% sign, insert arg2, and so on.


<?php  
$number = 123;  
$txt = sprintf("%f",$number);  
echo $txt;  
?>

3. Format digits 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 articles: