Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/241.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在数字的左边加零_Php - Fatal编程技术网

Php 如何在数字的左边加零

Php 如何在数字的左边加零,php,Php,我有一段代码可以把十进制数转换成基数3 $number = 10; // For Example $from_base = 10; $to_base = 3; $base_three = base_convert ( $number , $from_base , $to_base ); echo $base_three; 所以它回音的数字是101,有3个数字。 但我认为echos是000101,所以它有6个数字。 我的目标是将十进制转换为基数为3,并且始终是6位数字,即使它只有3或4位有用的

我有一段代码可以把十进制数转换成基数3

$number = 10; // For Example
$from_base = 10;
$to_base = 3;
$base_three = base_convert ( $number , $from_base ,  $to_base );
echo $base_three;
所以它回音的数字是101,有3个数字。 但我认为echos是000101,所以它有6个数字。
我的目标是将十进制转换为基数为3,并且始终是6位数字,即使它只有3或4位有用的数字!如何解决它?

您可以使用
sprintf
来确保它始终有6位数字,前导零为:

$base_three = 101;
$padded = sprintf("%06s", $base_three);
echo $padded;

您可以使用
sprintf
来确保它总有6位数字,前导零为:

$base_three = 101;
$padded = sprintf("%06s", $base_three);
echo $padded;

转换为字符串并用0填充

$test = str_pad($base_three, 6, '0', STR_PAD_LEFT);
echo $test;

转换为字符串并用0填充

$test = str_pad($base_three, 6, '0', STR_PAD_LEFT);
echo $test;
试试这个

echo str_pad($base_three, 6, "0", STR_PAD_LEFT);
试试这个

echo str_pad($base_three, 6, "0", STR_PAD_LEFT);

您可以使用sprintf确保始终输出6位数字,不管您有什么数字:

$number = 010;
sprintf("%06d", $number);
因此,完整的代码将是:

$number = 10; // For Example
$from_base = 10;
$to_base = 3;
$base_three = base_convert ( $number , $from_base ,  $to_base );
echo sprintf("%06d", $base_three);

printf格式化变量并将其回显,sprintf()不回显而是返回它


(s) printf可以做更多的工作,请参见

您可以使用sprintf确保始终输出6位数字,无论您有什么数字:

$number = 010;
sprintf("%06d", $number);
因此,完整的代码将是:

$number = 10; // For Example
$from_base = 10;
$to_base = 3;
$base_three = base_convert ( $number , $from_base ,  $to_base );
echo sprintf("%06d", $base_three);

printf格式化变量并将其回显,sprintf()不回显而是返回它

(s) printf可以做更多的工作,请参见