1
0
mirror of https://github.com/yattee/yattee.git synced 2024-12-15 23:00:32 +05:30
yattee/Extensions/Int+Format.swift

28 lines
761 B
Swift
Raw Normal View History

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