mirror of
https://github.com/yattee/yattee.git
synced 2025-08-05 02:04:07 +00:00
UI improvements
This commit is contained in:
@@ -2,28 +2,26 @@ import Foundation
|
||||
|
||||
extension Int {
|
||||
func formattedAsAbbreviation() -> String {
|
||||
typealias Abbrevation = (threshold: Double, divisor: Double, suffix: String)
|
||||
let abbreviations: [Abbrevation] = [
|
||||
(0, 1, ""), (1000.0, 1000.0, "K"),
|
||||
(999_999.0, 1_000_000.0, "M"), (999_999_999.0, 1_000_000_000.0, "B")
|
||||
]
|
||||
let num = fabs(Double(self))
|
||||
|
||||
let startValue = Double(abs(self))
|
||||
|
||||
guard let nextAbbreviationIndex = abbreviations.firstIndex(where: { startValue < $0.threshold }) else {
|
||||
guard num >= 1000.0 else {
|
||||
return String(self)
|
||||
}
|
||||
|
||||
let abbreviation = abbreviations[abbreviations.index(before: nextAbbreviationIndex)]
|
||||
let exp = Int(log10(num) / 3.0)
|
||||
let units = ["K", "M", "B", "T", "X"]
|
||||
let unit = units[exp - 1]
|
||||
|
||||
let formatter = NumberFormatter()
|
||||
|
||||
formatter.positiveSuffix = abbreviation.suffix
|
||||
formatter.negativeSuffix = abbreviation.suffix
|
||||
formatter.positiveSuffix = unit
|
||||
formatter.negativeSuffix = unit
|
||||
formatter.allowsFloats = true
|
||||
formatter.minimumIntegerDigits = 1
|
||||
formatter.minimumFractionDigits = 0
|
||||
formatter.maximumFractionDigits = 1
|
||||
|
||||
return formatter.string(from: NSNumber(value: Double(self) / abbreviation.divisor))!
|
||||
let roundedNum = round(10 * num / pow(1000.0, Double(exp))) / 10
|
||||
return formatter.string(from: NSNumber(value: roundedNum))!
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user