Skip to content

Instantly share code, notes, and snippets.

@maxcampolo
Created August 30, 2016 16:28
Show Gist options
  • Save maxcampolo/fd4094dcf78a079d5059c0f8b3462d32 to your computer and use it in GitHub Desktop.
Save maxcampolo/fd4094dcf78a079d5059c0f8b3462d32 to your computer and use it in GitHub Desktop.
Format a double into a short string with units suffix
extension Double {
var suffixNumber: String {
get {
var num = self
let sign = num < 0 ? "-" : ""
num = fabs(num)
if num < 1000.0 {
return "\(sign)\(Int(num))"
}
let exp = Int(log10(num) / 3.0 )
let units = ["K", "M", "G", "T", "P", "E"]
let roundedNum = round(10 * num / pow(1000.0, Double(exp))) / 10
return "\(sign)\(roundedNum)\(units[exp - 1])"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment