FeetAndInches
This commit is contained in:
@@ -563,28 +563,24 @@ extension UnitValue where ValueType: ConvertibleToDouble { // Apply constraints
|
||||
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? {
|
||||
public typealias FeetAndInches = (
|
||||
feet: UnitValue<Int>, inches: UnitValue<Double>
|
||||
)
|
||||
public var toFeetAndInches: FeetAndInches? {
|
||||
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"
|
||||
return (feet: feet.ft, inches: inches.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)
|
||||
public static func from(_ feetAndInches: FeetAndInches, to targetUnit: Unit)
|
||||
-> UnitValue<Double>?
|
||||
{
|
||||
guard targetUnit.category == .length else { return nil }
|
||||
let totalInches = Double(feet) * 12 + inches
|
||||
let (feet, inches) = feetAndInches
|
||||
let totalInches = Double(feet.value) * 12 + inches.value
|
||||
let inchesValue = totalInches.in
|
||||
return inchesValue.converted(to: targetUnit)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user