Skip to content

Instantly share code, notes, and snippets.

@jerrypm
Last active September 29, 2021 00:53
Show Gist options
  • Select an option

  • Save jerrypm/3a89a85dcfa61c4b45fba9db29f8cb26 to your computer and use it in GitHub Desktop.

Select an option

Save jerrypm/3a89a85dcfa61c4b45fba9db29f8cb26 to your computer and use it in GitHub Desktop.
import UIKit
class CurrencyViewController: UIViewController {
@IBOutlet weak var curent: UITextField!
@IBOutlet weak var resultValue: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .base
curent.addTarget(self, action: #selector(myTextFieldDidChange), for: .editingChanged)
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
@objc func myTextFieldDidChange(_ textField: UITextField) {
if let amountString = curent.text?.currencyInputFormatting() {
curent.text = amountString
}
}
@IBAction func didAddValue(_ sender: Any) {
resultValue.text = curent.text
curent.text = nil
}
}
extension String {
// formatting text for currency textField
func currencyInputFormatting() -> String {
var number: NSNumber!
let formatter = NumberFormatter()
formatter.numberStyle = .currencyAccounting
formatter.currencySymbol = "$"
formatter.maximumFractionDigits = 2
formatter.minimumFractionDigits = 2
var amountWithPrefix = self
// remove from String: "$", ".", ","
// for count string characters in swift2 use "self.characters.count" or swift4+ "self.count"
let regex = try! NSRegularExpression(pattern: "[^0-9]", options: .caseInsensitive)
amountWithPrefix = regex.stringByReplacingMatches(in: amountWithPrefix, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSMakeRange(0, self.count), withTemplate: "")
let double = (amountWithPrefix as NSString).doubleValue
number = NSNumber(value: (double / 100))
// if first number is 0 or all numbers were deleted
guard number != 0 as NSNumber else {
return ""
}
return formatter.string(from: number)!
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment