import Foundation
/*
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"
*/
func formatDecimalWithZeros(_ num: Double, _ width: Int, _ decimals: Int) -> String {
// Split into integer and fractional parts
let integer_part = Int(num)
let fractional_part = num - Double(integer_part)
// Format integer part with leading zeros
let int_str = String(format: "%0\(width)d", integer_part)
// Format fractional part (starts with "0.xxx")
let frac_str = String(format: "%.\(decimals)f", fractional_part)
// Remove the leading "0" before the decimal point
return int_str + frac_str.dropFirst()
}
let num = 3.14159
let result = formatDecimalWithZeros(num, 5, 5)
print("Original number: \(String(format: "%.5f", num))")
print("Formatted string: \(result)")
/*
run:
Original number: 3.14159
Formatted string: 00003.14159
*/