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

1 Answer

0 votes
program 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"
}

uses
    SysUtils; // Format // FormatFloat

function FormatDecimalWithZeros(num: Double; width, decimals: Integer): String;
var
    integer_part: Integer;
    fractional_part: Double;
    int_str, frac_str: String;
begin
    { Split into integer and fractional parts }
    integer_part := Trunc(num);
    fractional_part := num - integer_part;

    { Convert integer part with leading zeros }
    int_str := Format('%.*d', [width, integer_part]);

    { Convert fractional part (starts with "0.xxx") }
    frac_str := FormatFloat('0.' + StringOfChar('0', decimals), fractional_part);

    { Remove the leading "0" before the decimal point }
    FormatDecimalWithZeros := int_str + Copy(frac_str, 2, Length(frac_str));
end;

var
    num: Double;
    resultStr: String;

begin
    num := 3.14159;

    resultStr := FormatDecimalWithZeros(num, 5, 5);

    Writeln('Original number: ', num:0:5);
    Writeln('Formatted string: ', resultStr);
end.



{
run:
        
Original number: 3.14159
Formatted string: 00003.14159

}

 



answered 2 hours ago by avibootz
...