我有一个$counter
返回以下整数的变量:
4
我想使用数字格式或类似格式使我的整数以这种格式出现:
000,000,004
我该怎么做?
我有一个$counter
返回以下整数的变量:
4
我想使用数字格式或类似格式使我的整数以这种格式出现:
000,000,004
我该怎么做?
您可以像这样一起使用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
您可以使用str_pad功能:
str_pad((4,2,"0",STR_PAD_LEFT);
$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
*/
$number = 1;
echo number_format($number / 1000, 3, ",", "."); // 2 decimals, "," and "." as seperators
// gives 0,001