Home » Php » How to format numbers with 00 prefixes in php?

How to format numbers with 00 prefixes in php?

Posted by: admin April 23, 2020 Leave a comment

Questions:

I’m trying to generate invoice numbers. They should always be 4 numbers long, with leading zeros, for example :

  • 1 -> Invoice 0001
  • 10 -> Invoice 0010
  • 150 -> Invoice 0150

etc.

How to&Answers:

Use str_pad().

$invID = str_pad($invID, 4, '0', STR_PAD_LEFT);

Answer:

Use sprintf: http://php.net/function.sprintf

$number = 51;
$number = sprintf('%04d',$number);
print $number;
// outputs 0051


$number = 8051;
$number = sprintf('%04d',$number);
print $number;
// outputs 8051

Answer:

Use (s)printf

printf('%04d',$number);

Answer:

Try this:

$x = 1;
sprintf("%03d",$x);
echo $x;

Answer:

printf() works fine if you are always printing something, but sprintf() gives you more flexibility. If you were to use this function, the $threshold would be 4.

/**
 * Add leading zeros to a number, if necessary
 *
 * @var int $value The number to add leading zeros
 * @var int $threshold Threshold for adding leading zeros (number of digits 
 *                     that will prevent the adding of additional zeros)
 * @return string
 */
function add_leading_zero($value, $threshold = 2) {
    return sprintf('%0' . $threshold . 's', $value);
}

add_leading_zero(1);      // 01
add_leading_zero(5);      // 05
add_leading_zero(100);    // 100
add_leading_zero(1);      // 001
add_leading_zero(5, 3);   // 005
add_leading_zero(100, 3); // 100
add_leading_zero(1, 7);   // 0000001

Answer:

while ( strlen($invoice_number) < 4 ) $invoice_num = '0' . $invoice_num;

Answer:

Use the str_pad function

 //pad to left side of the input
$my_val=str_pad($num, 3, '0', STR_PAD_LEFT)

//pad to right side of the input
$my_val=str_pad($num, 3, '0', STR_PAD_RIGHT)

//pad to both side of the input
$my_val=str_pad($num, 3, '0', STR_PAD_BOTH)

where $num is your number