From 3798a3db326deca1747a0fdf1261d58f00973103 Mon Sep 17 00:00:00 2001 From: cdricms <36056008+cdricms@users.noreply.github.com> Date: Sun, 31 Aug 2025 18:10:59 +0200 Subject: [PATCH] To Feet and Inches --- Sources/Units/Units.swift | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/Sources/Units/Units.swift b/Sources/Units/Units.swift index 879d02f..ef98adf 100644 --- a/Sources/Units/Units.swift +++ b/Sources/Units/Units.swift @@ -558,3 +558,34 @@ extension UnitValue where ValueType: ConvertibleToDouble { // Apply constraints public var mph: UnitValue? { converted(to: .milesPerHour) } public var kn: UnitValue? { converted(to: .knots) } } + +// MARK: - Height Conversion Extensions +extension UnitValue where ValueType: ConvertibleToDouble { + /// Converts a length UnitValue (e.g., in cm) to feet and inches. + /// Returns nil if the category is not length. + public func toFeetAndInches(maximumFractionDigits: Int = 2) -> String? { + guard unit.category == .length else { return nil } + guard let totalInches = converted(to: .inch)?.value else { return nil } + let feet = Int(totalInches / 12) + let inches = totalInches.truncatingRemainder(dividingBy: 12) + let formatter = NumberFormatter() + formatter.maximumFractionDigits = maximumFractionDigits + formatter.minimumFractionDigits = 0 + formatter.numberStyle = .decimal + guard + let formattedInches = formatter.string( + from: NSNumber(value: inches)) + else { return nil } + return "\(feet) ft \(formattedInches) in" + } + + /// Creates a UnitValue in a target unit (e.g., cm) from feet and inches. + public static func from(feet: Int, inches: Double, to targetUnit: Unit) + -> UnitValue? + { + guard targetUnit.category == .length else { return nil } + let totalInches = Double(feet) * 12 + inches + let inchesValue = totalInches.in + return inchesValue.converted(to: targetUnit) + } +}