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

1 Answer

0 votes
/*
    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"
*/
def formatDecimalWithZeros(num: Double, width: Int, decimals: Int): String = {

    // Split into integer and fractional parts
    val integer_part = num.toInt
    val fractional_part = num - integer_part

    // Format integer part with leading zeros
    val int_str = String.format("%0" + width + "d", Integer.valueOf(integer_part))

    // Format fractional part (starts with "0.xxx")
    val frac_str = String.format("%." + decimals + "f", Double.box(fractional_part))

    // Remove the leading "0" before the decimal point
    int_str + frac_str.substring(1)
}

@main def run(): Unit = {
    val num = 3.14159

    val result = formatDecimalWithZeros(num, 5, 5)

    println("Original number: " + f"$num%.5f")
    println("Formatted string: " + result)
}



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

 



answered 18 hours ago by avibootz

Related questions

...