PHP number format 4 digits
23,747
Solution 1
It won't be a number (but a string), but you can do that using str_pad. In your examples:
$s_number = str_pad( "12", 4, "0", STR_PAD_LEFT );
$s_number = str_pad( "3", 4, "0", STR_PAD_LEFT );
Solution 2
Use str_pad()
for that:
echo str_pad($number, 4, '0', STR_PAD_LEFT);
Solution 3
You can achieve this easily by using phps' printf
<?php
$s_number = '12';
printf("%04d", $s_number);
?>
Hope this helps
Author by
Martelo2302
Updated on August 03, 2022Comments
-
Martelo2302 almost 2 years
For example, I have this format:
$s_number = "12";
And for this input, I need0012
as the output:Another example:
Input
$s_number = "3";
Output:0003
Every time I need 4 digits I would like this to happen.
-
Mic1780 about 11 yearsah thanks. Totally forgot they printf also prints it out (stupid of me cus it is also in the name of the function)
-
Martelo2302 about 11 yearsThank you, also I have succes with this $p = substr(sprintf('%04d', $digit),0,4);
-
hek2mgl about 11 yearsNote that str_pad is much faster ;)