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

前端 未结 2 1225
野的像风
野的像风 2020-12-16 11:51

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.

相关标签:
2条回答
  • 2020-12-16 11:54

    keep it simple

    echo sprintf("%'06.2f", 32.1);
    

    032.10

    0 讨论(0)
  • 2020-12-16 11:57

    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
    
    0 讨论(0)
提交回复
热议问题