Skip to content
Related Articles

Related Articles

Improve Article

How to properly Format a Number With Leading Zeros in PHP ?

  • Difficulty Level : Medium
  • Last Updated : 17 Jun, 2021
Geek Week

A number is essentially a sequence of digits stacked together to form an integer or string. A number can begin with leading zeros. A number can also be looped through and modifications can be made to append or concatenate another sequence of characters into it.

Approach 1: Using a for loop for string concatenation

A for loop can be iterated where the no. of iterations is equivalent to the number of zeros to lead the number with. During each iteration, a zero is appended to the front of the string. The time complexity is linear in terms of the number of zeros and is assumed to be constant for all practical purposes. 

PHP




<?php
    #declaring the number of zeros to lead the number
    $no_of_zeros = 4;
    #declaring the number
    $number = 999;
    print ("Original number : ");
    print ($number."\n"."<br>");
    #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);
?>
Output
Original number : 999
Modified number : 0000999

Approach 2: Conversion of integer to string



A string variable can be used as a substitute for storing numbers. The length of the number doesn’t have to be specified explicitly. PHP automatically coerces the type of the stored number. Also, explicit change of data types can be made by casting the type into the required format. 

However, the numeric data types have a limitation of storing the numbers without any leading zeros, therefore, all the zeros are removed as soon as the casting is done. The below code snippet illustrates this procedure.

PHP




<?php
  #declaring a number using a string with leading zeros
  $num = "00000092939292";
 
  #printing the number
  echo "Original Number \n";
  echo $num."\n"."<br>";
  echo "explicit casting.\n";
 
  #explicit casting
  echo (int)$num;
?>
Output
Original Number 
00000092939292
explicit casting.
92939292

Approach 3: Using str_pad() method 

This method will pad a string to a new length of the specified characters. In this case, the number is declared using a string variable. If the specified length is less than or equal to the original length of the string, no modifications are made to the original string. The str_pad() method is another alternative to performing repeated string concatenation. 

In this approach, we will use left padding to pad the string from left-hand side. The pad_type will be STR_PAD_LEFT and the pad_string will be equivalent to “0”. The length is equivalent to the length of the original string added to the number of zeros we wish to lead the number with. 

PHP




<?php
#specify the new length of the string
$len = 8;
 
#declare number using a string
$str = "2222";
echo("Original String \t");
echo ($str."\n");
 
#compute new string
$new_str = str_pad($str,$len,"0", STR_PAD_LEFT);
echo("Modified String \t");
echo $new_str;
?>
Output
Original String     2222
Modified String     00002222

Approach 4: Using format specifiers printf()/sprintf()

The printf() and sprintf() functions both results in a formatted string. A format is specified to output the number based on the leading character and the total length of the string. It is necessary to indicate the type of the number, that is, whether it is decimal, hexadecimal or octal, or so on. It is used to modify the number in such a way as to reflect the proper pattern of the number. At least one of the arguments is mandatory while calling this function. 

Syntax:

printf(format,arg1,arg2)

Parameters:

  • format (Required ): The string which format the variables.
  • arg1: A value to be inserted at the first % sign
  • arg2 (Optional): A value to be inserted at the second % sign

PHP




<?php
  #declaring the number
  $num = 86857658;
  print("Original Number : ");
  print($num."\n"."<br>");
 
  #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);
 
?>
Output
Original Number : 86857658
<br>Modified Number : 000000000086857658



My Personal Notes arrow_drop_up
Recommended Articles
Page :