具有不同格式的货币字符串的NumberFormatter?

时间:2018-02-09 23:36:26

标签: ios swift string number-formatting nsnumber

我正在撰写CurrencyNumberFormatter StringNSNumber并将其转换为与当前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”的案例?

0 个答案:

没有答案