1

I have the currency textfield that use this class. It works fine (show 1000000 -> 1,000,000). How can i convert back from currency string to double value? Please show me how to do, thank a lot.

import UIKit

class CurrencyTextField: UITextField {
    var lastValue = 0
    let maxValue = 1_000_000_000_000_000_000
    var amount: Int {
        if let newValue = Int(string.digits), newValue < maxValue {
            lastValue = newValue
        } else if !hasText {
            lastValue = 0
        }
        return lastValue
    }
    override func didMoveToSuperview() {
        textAlignment = .right
        keyboardType = .numberPad
        text = Formatter.decimal.string(for: amount)
        addTarget(self, action: #selector(editingChanged), for: .editingChanged)
    }
    @objc func editingChanged(_ textField: UITextField) {
        text = Formatter.decimal.string(for: amount)
    }
}

extension NumberFormatter {
    convenience init(numberStyle: Style) {
        self.init()
        self.numberStyle = numberStyle
    }
}
struct Formatter {
    static let decimal = NumberFormatter(numberStyle: .decimal)
}
extension UITextField {
    var string: String { return text ?? "" }
}

extension String {
    private static var digitsPattern = UnicodeScalar("0")..."9"
    var digits: String {
        return unicodeScalars.filter { String.digitsPattern ~= $0 }.string
    }
}

extension Sequence where Iterator.Element == UnicodeScalar {
    var string: String { return String(String.UnicodeScalarView(self)) }
}
Trung Nguyen
  • 138
  • 3
  • 14

1 Answers1

1

Based on the extensions you have shown in your code, this should work to convert your currency string into a Double value:

let doubleValue = Double(yourCurrencyString.digits)

Replace yourCurrencyString with whatever variable you're holding your currency string in.

clawesome
  • 1,223
  • 1
  • 5
  • 10