2021-08-31 21:17:50 +00:00
|
|
|
import Foundation
|
|
|
|
|
|
|
|
extension Int {
|
|
|
|
func formattedAsAbbreviation() -> String {
|
2021-11-11 21:07:13 +00:00
|
|
|
let num = fabs(Double(self))
|
2021-08-31 21:17:50 +00:00
|
|
|
|
2021-11-11 21:07:13 +00:00
|
|
|
guard num >= 1000.0 else {
|
2021-08-31 21:17:50 +00:00
|
|
|
return String(self)
|
|
|
|
}
|
|
|
|
|
2021-11-11 21:07:13 +00:00
|
|
|
let exp = Int(log10(num) / 3.0)
|
|
|
|
let units = ["K", "M", "B", "T", "X"]
|
|
|
|
let unit = units[exp - 1]
|
|
|
|
|
2021-08-31 21:17:50 +00:00
|
|
|
let formatter = NumberFormatter()
|
|
|
|
|
2021-11-11 21:07:13 +00:00
|
|
|
formatter.positiveSuffix = unit
|
|
|
|
formatter.negativeSuffix = unit
|
2021-08-31 21:17:50 +00:00
|
|
|
formatter.allowsFloats = true
|
|
|
|
formatter.minimumIntegerDigits = 1
|
|
|
|
formatter.minimumFractionDigits = 0
|
|
|
|
formatter.maximumFractionDigits = 1
|
|
|
|
|
2021-11-11 21:07:13 +00:00
|
|
|
let roundedNum = round(10 * num / pow(1000.0, Double(exp))) / 10
|
|
|
|
return formatter.string(from: NSNumber(value: roundedNum))!
|
2021-08-31 21:17:50 +00:00
|
|
|
}
|
|
|
|
}
|