PHP:如何通过 sprintf() 添加前导 zeros/zero 填充以浮动?

PHP: How to add leading zeros/zero padding to float via sprintf()?

我正在使用 sprintf() to get a formatted string of some float numbers with a certain precision. In addition, I wanted to add leading zeros to make all numbers even in length. Doing that for integers is pretty straight forward:

sprintf('%02d', 1);

这将导致 01。但是,对精确的浮点数进行同样的尝试是行不通的:

sprintf('%02.2f', 1);

产量 1.00

如何向浮点值添加前导零?

简答: sprintf('%05.2f', 1); 会得到想要的结果 01.00

请注意 %02 是如何被 %05 替换的。

说明

这个 forum post 给我指出了正确的方向:第一个数字既不表示前导零的数量,也不表示小数点分隔符左侧的总字符数 ,而是总的结果字符串中的字符数!

例子

sprintf('%02.2f', 1); 至少产生小数分隔符“.”加上至少 2 个字符的精度。由于总共已经是 3 个字符,所以开头的 %02 没有任何作用。要获得所需的“2 个前导零”,需要为精度和小数点分隔符添加 3 个字符,使其成为 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