Created
September 30, 2015 12:48
-
-
Save Igor-Palaguta/f8b95f3cd9ec58700d1d to your computer and use it in GitHub Desktop.
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
protocol AbbreviatedNumber { | |
var doubleValue: Double { get } | |
} | |
extension Int: AbbreviatedNumber { | |
var doubleValue: Double { | |
return Double(self) | |
} | |
} | |
extension Double: AbbreviatedNumber { | |
var doubleValue: Double { | |
return self | |
} | |
} | |
typealias AbbreviatedNumberFormatter = (Double, String) -> String | |
private let abbreviatedFormatter: NSNumberFormatter = { | |
let formatter = NSNumberFormatter() | |
formatter.maximumFractionDigits = 1 | |
formatter.roundingMode = .RoundDown | |
return formatter | |
}() | |
extension AbbreviatedNumber { | |
private func abbreviatedStringWithFormatter(formatter: AbbreviatedNumberFormatter) -> String { | |
let unit: Double = 1000 | |
let value = self.doubleValue | |
if value < unit { | |
return "\(self)" | |
} | |
let suffixes = ["K", "M", "B"] | |
let exp = min(Int(log(value) / log(unit)), suffixes.count) | |
let suffix = suffixes[exp - 1] | |
let prefixValue = value / pow(unit, Double(exp)) | |
return formatter(prefixValue, suffix) | |
} | |
func abbreviatedWithPrintfString() -> String { | |
return self.abbreviatedStringWithFormatter { | |
prefix, suffix in | |
return String(format: "%.1f%@", arguments: [prefix, suffix]) | |
} | |
} | |
func abbreviatedString() -> String { | |
return self.abbreviatedStringWithFormatter { | |
prefix, suffix in | |
return abbreviatedFormatter.stringFromNumber(NSNumber(double: prefix))!.stringByAppendingString(suffix) | |
} | |
} | |
} | |
1051.9.abbreviatedString() | |
123.abbreviatedString() | |
1234.abbreviatedString() | |
12345678.abbreviatedString() | |
123456789.abbreviatedString() | |
100_000_000_000_000.abbreviatedString() | |
1051.9.abbreviatedWithPrintfString() | |
123.abbreviatedWithPrintfString() | |
1234.abbreviatedWithPrintfString() | |
12345678.abbreviatedWithPrintfString() | |
123456789.abbreviatedWithPrintfString() | |
100_000_000_000_000.abbreviatedWithPrintfString() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment