Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add leading zeros and commas to a number in PHP

I have a variable $counter that returns the following integer:

4

I want to use number format or similar to make my integer appear in this format:

000,000,004

How can I this be done?

like image 706
harrynortham Avatar asked Dec 10 '25 21:12

harrynortham


2 Answers

You can use sprintf() and str_split() together like this:

$number = 4;
$formattedNumber = sprintf("%09d", $number);
$formattedNumber = str_split($formattedNumber, 3);
$formattedNumber = implode(",", $formattedNumber);
echo $formattedNumber;

Edit:

Here is a killer variant of the above code that uses str_pad():

function formatNumber($number, $desiredLength, $separatorLength) {
    $formattedNumber = str_pad($number, $desiredLength, "0", STR_PAD_LEFT);
    while(strlen($formattedNumber) % $separatorLength){
        $formattedNumber = " " . $formattedNumber;
    }
    $formattedNumber = str_split($formattedNumber, $separatorLength);
    $formattedNumber = implode(",", $formattedNumber);
    return trim($formattedNumber);
}
echo formatNumber(         4, 9, 3); // 000,000,004   -- fixed width
echo formatNumber(4000000000, 9, 3); // 4,000,000,000 -- fixed width; overflow handled automatically
echo formatNumber(         4, 0, 3); // 4             -- no width specified
echo formatNumber(      4000, 0, 3); // 4,000         -- no width specified; comma added automatically
like image 61
Salman A Avatar answered Dec 12 '25 10:12

Salman A


One method you can do is sprintf.

sprintf('%03d', $counter);

another is using str_pad

str_pad($counter, 3, "0", STR_PAD_LEFT);
like image 22
Jishnu Avatar answered Dec 12 '25 09:12

Jishnu