问题
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.
回答1:
Use str_pad().
$invID = str_pad($invID, 4, '0', STR_PAD_LEFT);
回答2:
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
回答3:
Use (s)printf
printf('%04d',$number);
回答4:
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
回答5:
Try this:
$x = 1;
sprintf("%03d",$x);
echo $x;
回答6:
while ( strlen($invoice_number) < 4 ) $invoice_num = '0' . $invoice_num;
回答7:
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
来源:https://stackoverflow.com/questions/6296822/how-to-format-numbers-with-00-prefixes-in-php