Created
August 30, 2016 16:28
-
-
Save maxcampolo/fd4094dcf78a079d5059c0f8b3462d32 to your computer and use it in GitHub Desktop.
Format a double into a short string with units suffix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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