将字符串转换为货币Swift

时间:2018-11-23 14:42:08

标签: swift currency-formatting

我无法将String数组转换为Currency。

enter image description here

enter image description here

我已经创建了扩展名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)!

}

3 个答案:

答案 0 :(得分:4)

您不需要使用正则表达式替换任何字符。只需使用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
            if let str = formatter.string(for: value) {
                return str
            }
        }
        return ""
    }
}

"74154.7".currencyFormatting()            // $74,154.70

"74719.4048014544".currencyFormatting()   // $74,719.40

答案 1 :(得分:2)

您可以使用以下功能获取有效的货币格式-

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

答案 2 :(得分:-1)

尝试一下

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