How to format numbers with 00 prefixes in php? – Here in this article, we will share some of the most common and frequently asked about PHP problem in programming with detailed answers and code samples. There’s nothing quite so frustrating as being faced with PHP errors and being unable to figure out what is preventing your website from functioning as it should like php and numbers . If you have an existing PHP-based website or application that is experiencing performance issues, let’s get thinking about How to format numbers with 00 prefixes in php?.
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.
Solution :
Use str_pad().
$invID = str_pad($invID, 4, '0', STR_PAD_LEFT);
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
Use (s)printf
printf('%04d',$number);
Try this:
$x = 1;
sprintf("%03d",$x);
echo $x;
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
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
while ( strlen($invoice_number) < 4 ) $invoice_num = '0' . $invoice_num;