Created
January 11, 2023 09:50
-
-
Save lalkrishna/08964fa0cf3c0f1be7bd9e90cf13ee4c to your computer and use it in GitHub Desktop.
amount formatter based on user's locale.
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
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