How to express a decimal number as a fixed-length string with leading zeros in PHP

1 Answer

0 votes
class FormatDecimalWithZeros {

    /*
        format_decimal_with_zeros
        -------------------------
        Converts a floating‑point number into a fixed‑length string with
        leading zeros on the integer part.

        Parameters:
            num          - the decimal number to format
            width        - total width of the integer part (zero‑padded)
            decimals     - number of digits after the decimal point

        Returns:
            A formatted string such as "00003.14159"

        Example:
            num = 3.14159, width = 5, decimals = 5
            Output → "00003.14159"
    */
    public static function formatDecimalWithZeros(float $num, int $width, int $decimals): string {

        // Split into integer and fractional parts
        $integer_part = (int) $num;
        $fractional_part = $num - $integer_part;

        // Format integer part with leading zeros
        $int_str = sprintf("%0{$width}d", $integer_part);

        // Format fractional part (starts with "0.xxx")
        $frac_str = sprintf("%.{$decimals}f", $fractional_part);

        // Remove the leading "0" before the decimal point
        return $int_str . substr($frac_str, 1);
    }
}

$num = 3.14159;

$result = FormatDecimalWithZeros::formatDecimalWithZeros($num, 5, 5);

echo "Original number: " . sprintf("%.5f", $num) . PHP_EOL;
echo "Formatted string: " . $result . PHP_EOL;



/*
run:
             
Original number: 3.14159
Formatted string: 00003.14159
         
*/

 



answered 3 hours ago by avibootz

Related questions

...