I was trying to write a function that returns a localized string for a weight measurement - but with the option of skipping the unit substring. As in: return "100,1" instead of "100,1kg" but respecting the user's locale.
First thought was: just specify unitStyle = .none but that is not a valid member.
So I came up with this solution which works for pounds and kilos but there sure are other weight / mass units out there... How do I retrieve the user's preferred unit from locale?
First thought was: just specify unitStyle = .none but that is not a valid member.
So I came up with this solution which works for pounds and kilos but there sure are other weight / mass units out there... How do I retrieve the user's preferred unit from locale?
Code Block func formatWeight(weightInKgs value: Double, skipUnit: Bool = false) -> String { let weightInKgs = Measurement(value: value, unit: UnitMass.kilograms) if !skipUnit { let formatter = MeasurementFormatter() // if skipUnit { // formatter.unitStyle = .none // } else { formatter.unitStyle = .short // } formatter.numberFormatter.maximumFractionDigits = 1 formatter.numberFormatter.minimumFractionDigits = 1 return formatter.string(from: weightInKgs) } else { if Locale.current.usesMetricSystem { let formatter = NumberFormatter() formatter.maximumFractionDigits = 1 formatter.minimumFractionDigits = 1 return formatter.string(from: NSNumber(value: weightInKgs.value))! } else { let weightInLocaleUnit = weightInKgs.converted(to: UnitMass.pounds) //this is not universal let formatter = NumberFormatter() formatter.maximumFractionDigits = 1 formatter.minimumFractionDigits = 1 return formatter.string(from: NSNumber(value: weightInLocaleUnit.value))! } } }