zerofill整数php

dot*_*tty 26 php integer autofill zero fill

我如何进行"零填充"整数?

1 becomes 0001
40 becomes 0040
174 becomes 0174
Run Code Online (Sandbox Code Playgroud)

Pal*_*tir 71

$filled_int = sprintf("%04d", $your_int)
Run Code Online (Sandbox Code Playgroud)

  • 还有http://php.net/manual/en/function.str-pad.php,就像旁注一样. (3认同)
  • 如果你想为 15 位数字补零,应该是这样的: $filled_int = sprintf("%015d", $your_int) (2认同)

Joe*_*Joe 22

$number = 12;
$width = 4;
$padded = str_pad((string)$number, $width, "0", STR_PAD_LEFT); 
Run Code Online (Sandbox Code Playgroud)

  • 根据具体情况,我认为这通常是更好的解决方案.此外,除非在`str_pad`中使用数字文字,否则当前不需要显式转换为`string`.将隐式转换数值类型的变量. (2认同)