📜  如何在PHP中正确格式化带有前导零的数字?

📅  最后修改于: 2022-05-13 01:56:29.906000             🧑  作者: Mango

如何在PHP中正确格式化带有前导零的数字?

数字本质上是堆叠在一起形成整数或字符串的数字序列。数字可以以前导零开头。也可以循环一个数字,并且可以进行修改以将另一个字符序列附加或连接到其中。

方法 1:使用 for 循环进行字符串连接

可以在没有的地方迭代一个 for 循环。迭代次数等于引导数字的零的数量。在每次迭代期间,将零附加到字符串的前面。时间复杂度就零的数量而言是线性的,并且对于所有实际目的都假定为常数。

PHP
");
    #leading the number with indicated zeros
    for($i=1;$i<=$no_of_zeros;$i++)
    {
      #concatenating 0 string in front of number
      $number = '0'.$number;
    }
    print ("Modified number : ");
    print ($number);
?>


PHP
";
  echo "explicit casting.\n";
 
  #explicit casting
  echo (int)$num;
?>


PHP


PHP
");
 
  #specifying the number of zeros
  $num_of_zeros = 10;
 
  #defining the total length of the number of
  #zeros and length of the number
  $length = $num_of_zeros + strlen($num) ;
 
  #defining the character to lead the number with
  $ch = 0;
 
  #specifying the type of number
  $num_type = 'd';
 
  #specifying the format
  $format_specifier = "%{$ch}{$length}{$num_type}";
 
  # print and echo
  print("Modified Number : ");
  printf($format_specifier, $num);
 
?>


输出
Original number : 999
Modified number : 0000999

方法2:整数到字符串的转换

字符串变量可以用作存储数字的替代品。不必明确指定数字的长度。 PHP自动强制存储数字的类型。此外,可以通过将类型转换为所需格式来显式更改数据类型。

但是,数字数据类型在存储数字时没有任何前导零的限制,因此,一旦完成转换,所有零都会被删除。下面的代码片段说明了这个过程。

PHP

";
  echo "explicit casting.\n";
 
  #explicit casting
  echo (int)$num;
?>
输出
Original Number 
00000092939292
explicit casting.
92939292

方法 3:使用str_pad()方法

此方法会将字符串填充到指定字符的新长度。在这种情况下,数字是使用字符串变量声明的。如果指定的长度小于或等于字符串的原始长度,则不对原始字符串进行任何修改。 str_pad()方法是执行重复字符串连接的另一种替代方法。

在这种方法中,我们将使用左填充从左侧填充字符串。 pad_type将为 STR_PAD_LEFT, pad_string将等同于“0”。长度等于原始字符串的长度加上我们希望以数字开头的零的数量。

PHP


输出
Original String     2222
Modified String     00002222

方法 4:使用格式说明符printf()/sprintf()

printf()sprintf()函数都生成格式化字符串。指定格式以根据前导字符和字符串的总长度输出数字。需要指明数字的类型,即是十进制、十六进制还是八进制等等。它用于修改数字以反映数字的正确模式。调用此函数时,至少有一个参数是必需的。

句法:

printf(format,arg1,arg2)

参数:

  • 格式(必需):格式化变量的字符串。
  • arg1:要在第一个 % 符号处插入的值
  • arg2(可选):要在第二个 % 符号处插入的值

PHP

");
 
  #specifying the number of zeros
  $num_of_zeros = 10;
 
  #defining the total length of the number of
  #zeros and length of the number
  $length = $num_of_zeros + strlen($num) ;
 
  #defining the character to lead the number with
  $ch = 0;
 
  #specifying the type of number
  $num_type = 'd';
 
  #specifying the format
  $format_specifier = "%{$ch}{$length}{$num_type}";
 
  # print and echo
  print("Modified Number : ");
  printf($format_specifier, $num);
 
?>
输出
Original Number : 86857658

Modified Number : 000000000086857658