如何在PHP中的数字中添加前导零和逗号

时间:2012-07-17 08:51:45

标签: php integer format number-formatting

我有一个变量$counter,它返回以下整数:

4

我想使用数字格式或类似格式使我的整数以这种格式显示:

000,000,004

我该怎么做?

5 个答案:

答案 0 :(得分:5)

您可以像这样使用sprintf()str_split()

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

编辑:

以上是使用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

答案 1 :(得分:2)

您可以执行的一种方法是sprintf

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

另一个是使用str_pad

str_pad($counter, 3, "0", STR_PAD_LEFT);

答案 2 :(得分:0)

您可以使用str_pad功能:

str_pad((4,2,"0",STR_PAD_LEFT);

答案 3 :(得分:0)

$string = "4";
echo str_pad($string, 9, "0", STR_PAD_LEFT); // prints "000000004" (9-digit number)

/* 
   9 = How long the returned value should be. Must be bigger than length of $string
   0 = String to add
   STR_PAD_LEFT = On which side to add zeros? Left, in the case
 */

答案 4 :(得分:0)

使用number_format

$number = 1;
echo number_format($number / 1000, 3, ",", "."); // 2 decimals, "," and "." as seperators
// gives 0,001