PHP:如何添加前导零/零填充以通过sprintf()浮动?
2022-08-30 17:43:13
简短的回答:会给出想要的结果sprintf('%05.2f', 1);
01.00
请注意如何被 替换为 。%02
%05
解释
这篇论坛帖子为我指出了正确的方向:第一个数字既不表示前导零的数量,也不表示十进制分隔符左侧的总字符数,而是结果字符串中的字符总数!
例
sprintf('%02.2f', 1);
至少生成十进制分隔符 “” 加上至少 2 个字符的精度。由于这已经是总共3个字符,因此在开始时不起作用。要获得所需的“2个前导零”,需要添加3个字符以获得精度和十进制分隔符,使其成为.
%02
sprintf('%05.2f', 1);
一些代码
$num = 42.0815;
function printFloatWithLeadingZeros($num, $precision = 2, $leadingZeros = 0){
$decimalSeperator = ".";
$adjustedLeadingZeros = $leadingZeros + mb_strlen($decimalSeperator) + $precision;
$pattern = "%0{$adjustedLeadingZeros}{$decimalSeperator}{$precision}f";
return sprintf($pattern,$num);
}
for($i = 0; $i <= 6; $i++){
echo "$i max. leading zeros on $num = ".printFloatWithLeadingZeros($num,2,$i)."\n";
}
输出
0 max. leading zeros on 42.0815 = 42.08
1 max. leading zeros on 42.0815 = 42.08
2 max. leading zeros on 42.0815 = 42.08
3 max. leading zeros on 42.0815 = 042.08
4 max. leading zeros on 42.0815 = 0042.08
5 max. leading zeros on 42.0815 = 00042.08
6 max. leading zeros on 42.0815 = 000042.08
保持简单
echo sprintf("%'06.2f", 32.1);
032.10