将字符串转换为货币 Swift

Converting String to Currency Swift

我在将字符串数组转换为货币时遇到问题。

我创建了一个扩展 currencyInputFormatting()。但是,逗号被放置在错误的位置。

这是我的代码:-

cell.balanceLabel.text? = (monthlyBalanceStringArray)[indexPath.row].currencyFormatting()

extension String {

    // formatting text for currency textField
    func currencyFormatting() -> String {

        var number: NSNumber!
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.maximumFractionDigits = 2

        var amountWithPrefix = self

        let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive)
        amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.characters.count), withTemplate: "")

        let double = (amountWithPrefix as NSString).doubleValue
        number = NSNumber(value: (double))

        //    number = NSNumber(value: (double / 100))

        guard number != 0 as NSNumber else {
            return ""
        }

        return formatter.string(from: number)!
    }
}

您无需使用正则表达式替换任何字符。只需使用 NSNumberFormatter

extension String {
    // formatting text for currency textField
    func currencyFormatting() -> String {
        if let value = Double(self) {
            let formatter = NumberFormatter()
            formatter.numberStyle = .currency
            formatter.maximumFractionDigits = 2
            formatter.minimumFractionDigits = 2
            if let str = formatter.string(for: value) {
                return str
            }
        }
        return ""
    }
}

"74154.7".currencyFormatting()            // ,154.70

"74719.4048014544".currencyFormatting()   // ,719.40

You can use following function for valid currency format -

 extension Int {
    func createCurrencyString() -> String {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.maximumFractionDigits = 0
        return formatter.string(from: NSNumber(value: self))!
    }
}