php 如何在php中格式化带有00前缀的数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6296822/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to format numbers with 00 prefixes in php?
提问by mike23
I'm trying to generate invoice numbers. They should always be 4 numbers long, with leading zeros, for example :
我正在尝试生成发票编号。它们应该总是 4 个数字长,前导零,例如:
- 1 -> Invoice 0001
- 10 -> Invoice 0010
- 150 -> Invoice 0150
- 1 -> 发票 0001
- 10 -> 发票 0010
- 150 -> 发票 0150
etc.
等等。
回答by Wiseguy
回答by Chris Baker
Use sprintf
: http://php.net/function.sprintf
使用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
回答by Dave
Try this:
尝试这个:
$x = 1;
sprintf("%03d",$x);
echo $x;
回答by webjawns.com
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.
printf()
如果您总是打印一些东西,效果很好,但sprintf()
会给您更多的灵活性。如果您要使用此函数,$threshold
则为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
回答by Sani Kamal
Use the str_padfunction
使用str_pad函数
//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
$num 是你的号码
回答by user769573
while ( strlen($invoice_number) < 4 ) $invoice_num = '0' . $invoice_num;