0

How to format the price textfield text as a currency format like 234,345,567 and also I need to restrict the decimal points to not more than 2 and also to append $ symbol when user starts typing.

for example : $234,345,678.25

like this I want to add comma between 3numbers when they type the amount in textfield

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {


if ((string == "0" || string == "") && (txtFldPostalCode.text! as NSString).range(of: ".").location < range.location) {
  return true
}
let cs = NSCharacterSet(charactersIn: "0123456789.").inverted
let filtered = string.components(separatedBy: cs)
let component = filtered.joined(separator: "")
let isNumeric = string == component
if isNumeric {
  let formatter = NumberFormatter()
  formatter.numberStyle = .decimal
  formatter.maximumFractionDigits = 8
  let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
  let numberWithOutCommas = newString.replacingOccurrences(of: ",", with: "")
  let number = formatter.number(from: numberWithOutCommas)
  if number != nil {
    var formattedString = formatter.string(from: number!)
    if string == "." && range.location == textField.text?.length {
      formattedString = formattedString?.appending(".")
    }
    textField.text = formattedString
  } else {
    textField.text = nil
  }
}
return false

}

Sneha
  • 2,200
  • 6
  • 22
  • 36
Naren Krish
  • 259
  • 2
  • 14

1 Answers1

3

For Swift 3. Input currency format on a text field (from right to left)

@IBOutlet weak var textfield: UITextField!


override func viewDidLoad() {
    super.viewDidLoad()

    textfield.addTarget(self, action: #selector(myTextFieldDidChange), for: .editingChanged)
    // Do any additional setup after loading the view.
}
@objc func myTextFieldDidChange(_ textField: UITextField) {

    if let amountString = textField.text?.currencyInputFormatting() {
        textField.text = amountString
    }
}
}
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

    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 / 100))


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

    return formatter.string(from: number)!
}

Hope this is helpful...

tabassum
  • 1,100
  • 6
  • 17
  • I want this from left to right but I dint want that decimal, I have tried with this already.if I put decimal I have to restrict this with 2 digits – Naren Krish Feb 08 '18 at 11:08
  • what u want i m not getting you??as u asked in question i want decimal point not more than 2 ...so in my answer it is restricted to 2 digit only – tabassum Feb 08 '18 at 11:24