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

Short answer: sprintf('%05.2f', 1); will give the desired result 01.00

Note how %02 was replaced by %05.

Explanation

This forum post pointed me in the right direction: The first number does neither denote the number of leading zeros nor the number of total charaters to the left of the decimal seperator but the total number of characters in the resulting string!

Example

sprintf('%02.2f', 1); yields at least the decimal seperator "." plus at least 2 characters for the precision. Since that is already 3 characters in total, the %02 in the beginning has no effect. To get the desired "2 leading zeros" one needs to add the 3 characters for precision and decimal seperator, making it sprintf('%05.2f', 1);

Some code

$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";
}

Output

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