我正在撰写CurrencyNumberFormatter
String
或NSNumber
并将其转换为与当前Locale
相关的预期结果。
这是我的解决方案。
final class CurrencyNumberFormatter {
/// Locale of a `CurrencyNumberFormatter`.
var locale: Locale
/// numberFormatter of a `CurrencyNumberFormatter`.
private var numberFormatter: NumberFormatter
/// Initializes a `CurrencyNumberFormatter` with a `Locale`.
init(locale: Locale = .current) {
self.locale = locale
self.numberFormatter = NumberFormatter()
self.numberFormatter.locale = self.locale
self.numberFormatter.numberStyle = .currency
self.numberFormatter.isLenient = true
}
/// Converts a String to a `NSumber`.
///
/// - Parameters:
/// - string: string to convert.
/// - Returns: `NSumber` represenation.
func number(from string: String) -> NSNumber? {
return self.numberFormatter.number(from: string)
}
/// Converts a NSumber to a `String`.
///
/// - Parameters:
/// - number: nsnumber to convert.
/// - Returns: `NSumber` represenation.
func string(from number: NSNumber) -> String? {
return self.numberFormatter.string(from: number)
}
}
用法:
let currensy = CurrencyNumberFormatter()
currensy.number(from: "1000.25") // 1000.25
currensy.number(from: "1,000.25") // 1000.25
currensy.number(from: "1.000,25") // nil -> 1000.25
currensy.number(from: "1'000,25") // nil -> 1000.25
currensy.number(from: ",25") // 25 -> 0.25
currensy.number(from: ".25") // 0.25
如何处理“1.000,25”,“1'000,25”,“,25”的案例?