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

Share:
23,747
Martelo2302
Author by

Martelo2302

Updated on August 03, 2022

Comments

  • Martelo2302
    Martelo2302 almost 2 years

    For example, I have this format: $s_number = "12"; And for this input, I need 0012 as the output:

    Another example:

    Input $s_number = "3"; Output: 0003

    Every time I need 4 digits I would like this to happen.

  • Mic1780
    Mic1780 about 11 years
    ah thanks. Totally forgot they printf also prints it out (stupid of me cus it is also in the name of the function)
  • Martelo2302
    Martelo2302 about 11 years
    Thank you, also I have succes with this $p = substr(sprintf('%04d', $digit),0,4);
  • hek2mgl
    hek2mgl about 11 years
    Note that str_pad is much faster ;)