How can I add custom init method for String extension?
extension String {
init(_ amount: Double, decimalPlaces: UInt) {
self.init()
let decimalFormat = "%0.\(String(decimalPlaces))f"
let currencyAmount = String(format: decimalFormat, amount)
let currencySign = NSLocalizedString("Defaults.CurrencySign", comment: "currency sign")
let formattedString = "\(currencySign)\(currencyAmount)"
// How to set self to `formattedString` ?
}
}
As result I want to see something like this:
let price = Double(155.15)
let formattedPrice = String(price, decimalPlaces: 2) // formattedPrice = "$155.15"
UPDATED: Final solution
extension String {
init?(currencyAmount: Double) {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.locale = Locale(identifier: NSLocalizedString("Defaults.LocaleCurrencyFormat", comment: "currency sign")) // Defaults.LocaleCurrencyFormat equal "es_US" for US
let formattedAmount = formatter.string(from: NSNumber(value: currencyAmount)) ?? ""
self.init(formattedAmount)
}
}
However you might think currencies are formatted, you're almost certainly wrong. Just compare:
$3,490,000.89
3 490 000,89 $
3 490 000,89 €
3.490.000,89 €
Instead, use NumberFormatter
with numberStyle
set to .currency
, with a specified locale.
let currencyFormatter = NumberFormatter()
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.numberStyle = .currency
currencyFormatter.locale = Locale.current
let priceString = currencyFormatter.string(from: 9999.99)!
print(priceString) // Displays $9,999.99 in the US locale
The initializers (and mutating methods) of value types can simply assign directly to self
:
import Foundation
extension String {
init(_ amount: Double, decimalPlaces: UInt) {
let currencyAmount = String(format: "%\(decimalPlaces).f", amount)
let currencySign = NSLocalizedString("Defaults.CurrencySign", comment: "currency sign")
self = "\(currencySign)\(currencyAmount)"
}
}
let price = Double(155.15)
let formattedPrice = String(price, decimalPlaces: 2) // formattedPrice = "$155.15"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With