I have a distance as a float and I\'m looking for a way to format it nicely for human readers. Ideally, I\'d like it to change from m to km as it gets bigger, and to round the n
For those looking for a swift 2.0 version. Ported from @MattDiPasquale
extension Double {
func toDistanceString() -> String {
let METERS_TO_FEET = 3.2808399
let METERS_CUTOFF = 1000.0
let FEET_CUTOFF = 3281.0
let FEET_IN_MILES = 5280.0
let format:String
if (NSLocale.isMetric()) {
if (self < METERS_CUTOFF) {
format = "\(self.stringWithDecimals(0)) metres"
} else {
format = "\((self / 1000).stringWithDecimals(1)) km";
}
} else { // assume Imperial / U.S.
let feet = self * METERS_TO_FEET;
if (feet < FEET_CUTOFF) {
format = "\(feet.stringWithDecimals(0)) feet";
} else {
format = "\((self / FEET_IN_MILES).stringWithDecimals(1)) miles";
}
}
return format
}
func stringWithDecimals(decimals:Int) -> String {
return String(format: "%.\(decimals)f", self)
}
}
extension NSLocale {
class func isMetric() -> Bool {
let locale = NSLocale.currentLocale()
return locale.objectForKey(NSLocaleUsesMetricSystem) as! Bool
}
}