Skip to content

Instantly share code, notes, and snippets.

@lalkrishna
Created January 11, 2023 09:50
Show Gist options
  • Save lalkrishna/08964fa0cf3c0f1be7bd9e90cf13ee4c to your computer and use it in GitHub Desktop.
Save lalkrishna/08964fa0cf3c0f1be7bd9e90cf13ee4c to your computer and use it in GitHub Desktop.
amount formatter based on user's locale.
extension Double {
func formattedAsCurrency(_ currencySymbol: String? = nil) -> String {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: "id_ID")
if let currencySymbol {
formatter.currencySymbol = currencySymbol
}
let price = NSNumber(value: self)
if let amountString = formatter.string(from: price) {
// check if it has default space like EUR
let hasSpace = amountString.rangeOfCharacter(from: .whitespaces) != nil
// let searchSymbol = self < 0 ? "-" + formatter.currencySymbol : formatter.currencySymbol!
if let rangeOfSymbol = amountString.range(of: formatter.currencySymbol) {
if amountString.startIndex == rangeOfSymbol.lowerBound {
formatter.paddingPosition = .afterPrefix
} else {
formatter.paddingPosition = .beforeSuffix
}
}
if !hasSpace {
formatter.formatWidth = amountString.count + 1
formatter.paddingCharacter = " "
}
} else {
AppLogger.log("Error while making amount string from value: \(self)")
return "\(self)"
}
return formatter.string(from: price) ?? "\(self)"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment