Search code examples
swiftxcodecurrency-formatting

Converting String to Currency Swift


I am having trouble converting my array of String to Currency.

enter image description here

enter image description here

I have created an extension currencyInputFormatting(). However, the commas are being placed in the wrong spots.

Here is my code :-

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)!
    }
}

Solution

  • You don't need to replace any any characters using regex. Just use 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()            // $74,154.70
    
    "74719.4048014544".currencyFormatting()   // $74,719.40