To Feet and Inches

This commit is contained in:
cdricms
2025-08-31 18:10:59 +02:00
parent 2dfdf5572f
commit 3798a3db32

View File

@@ -558,3 +558,34 @@ extension UnitValue where ValueType: ConvertibleToDouble { // Apply constraints
public var mph: UnitValue<Double>? { converted(to: .milesPerHour) }
public var kn: UnitValue<Double>? { 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<Double>?
{
guard targetUnit.category == .length else { return nil }
let totalInches = Double(feet) * 12 + inches
let inchesValue = totalInches.in
return inchesValue.converted(to: targetUnit)
}
}