Last active
May 13, 2025 05:41
-
-
Save hey-amo/b4de63e22b8429728ba9a4eeb478ef10 to your computer and use it in GitHub Desktop.
Cached NumberFormatter
This file contains hidden or 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
/// NumberFormatter is quite expensive to run each time, | |
/// so lets make a cache to hold it | |
/// | |
struct FormatterCache { | |
static let currency: NumberFormatter = { | |
let formatter = NumberFormatter() | |
formatter.locale = Locale(identifier: "en_US") | |
formatter.numberStyle = .currency | |
formatter.minimumFractionDigits = 0 | |
formatter.maximumFractionDigits = 0 | |
formatter.allowsFloats = false | |
formatter.roundingMode = .ceiling | |
formatter.alwaysShowsDecimalSeparator = false | |
return formatter | |
}() | |
} | |
// Add extension on double | |
extension Double { | |
var formattedAsCurrency: String { | |
return FormatterCache.currency.string(from: NSNumber(value: self)) ?? "$???" | |
} | |
} | |
// Usage | |
let baseSalary = 95_000 | |
print (baseSalary.formattedAsCurrency) | |
// -- possible alternative to handle different currencies -- | |
struct AltFormatterCache { | |
private static var formatters: [String: NumberFormatter] = [:] | |
static func currency(for localeID: String) -> NumberFormatter { | |
if let cached = formatters[localeID] { return cached } | |
let formatter = NumberFormatter() | |
formatter.locale = Locale(identifier: localeID) | |
formatter.numberStyle = .currency | |
formatter.minimumFractionDigits = 0 | |
formatter.maximumFractionDigits = 0 | |
formatters[localeID] = formatter | |
return formatter | |
} | |
} | |
let locale = "en_GB" // this could be from user profile, region settings, etc. | |
let salary = 95000.0 | |
let formatted = AltFormatterCache.currency(for: locale).string(from: NSNumber(value: salary)) ?? "?" | |
print (formatted) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment