How to add zeros to the left of a number [duplicat

2020-07-24 03:49发布

I have a piece of code for converting a Decimal number into base 3

$number = 10; // For Example
$from_base = 10;
$to_base = 3;
$base_three = base_convert ( $number , $from_base ,  $to_base );
echo $base_three;

So the number that it echos is 101 and it has 3 digits. but I what it to echos is 000101 so that it has 6 digits. Converting Decimal into base 3 with always 6 digits even though it has only 3 or 4 useful digits, is my goal! how can I solve it ?

标签: php
4条回答
男人必须洒脱
2楼-- · 2020-07-24 04:25

try this

echo str_pad($base_three, 6, "0", STR_PAD_LEFT);
查看更多
男人必须洒脱
3楼-- · 2020-07-24 04:29

You can use sprintf to ensure that it always has a total of 6 digits, with leading zeroes:

$base_three = 101;
$padded = sprintf("%06s", $base_three);
echo $padded;
查看更多
【Aperson】
4楼-- · 2020-07-24 04:37

Convert to a string and pad with 0's.

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

http://php.net/manual/en/function.str-pad.php

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-07-24 04:40

You can use sprintf to make sure you always output 6 digits, whatever number you have:

$number = 010;
sprintf("%06d", $number);

so the complete piece of code would be:

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

or

printf("%06d", $base_three);

printf formats the variable and echos it, sprintf() doesn't echo but returns it

(s)printf can do a lot more, see http://www.php.net/manual/en/function.sprintf.php

查看更多
登录 后发表回答