3

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

4

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

000,000,004

我该怎么做?

4

5 回答 5

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
于 2012-07-17T08:57:29.247 回答
2

您可以做的一种方法是sprintf

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

另一个正在使用str_pad

str_pad($counter, 3, "0", STR_PAD_LEFT);
于 2012-07-17T09:00:35.563 回答
0

您可以使用str_pad功能:

str_pad((4,2,"0",STR_PAD_LEFT);
于 2012-07-17T09:00:29.537 回答
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
 */
于 2012-07-17T09:19:02.257 回答
0

使用 number_format

$number = 1;
echo number_format($number / 1000, 3, ",", "."); // 2 decimals, "," and "." as seperators
// gives 0,001
于 2015-01-07T18:18:08.270 回答