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

13,243

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
Share:
13,243

Related videos on Youtube

Hirnhamster
Author by

Hirnhamster

Usual stack: Ubuntu / Debian PHP MySQL Redis Laravel More at https://www.pascallandau.com/.

Updated on September 15, 2022

Comments

  • Hirnhamster
    Hirnhamster over 1 year

    I'm using 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);
    

    This will result in 01. However, trying the same for a float with precision doesn't work:

    sprintf('%02.2f', 1);
    

    Yields 1.00.

    How can I add leading zeros to a float value?

  • mickmackusa
    mickmackusa about 2 years
    echo sprintf() is an "antipattern". There is absolutely no reason that anyone should ever write echo sprintf() -- it should be printf() without echo every time.