1

I have a textfield that it's input is price, so I want to get both like this: 1,111,999.99. I wrote to make it possible but there are two problems. First, after four digits and 2 fraction digit (like 1,234.00) it resets to zero. Second, I can't put fraction in it (fraction is always .00) how can i make a textfield that receives 1,111,999.99 as input?

in my custom UITextfield:

private var numberFormatter: NumberFormatter {
    let formatter = NumberFormatter()
    formatter.maximumFractionDigits = 2
    formatter.minimumFractionDigits = 0
    formatter.numberStyle = .decimal
    formatter.decimalSeparator = "."
    formatter.groupingSeparator = ","
    return formatter
}

var commaValue: String {
    return numberFormatter.string(from: value)!
}

var value: NSNumber {
    let number = numberFormatter.number(from: self.text ?? "0")
    return number!
}

and in my textfieldDidChange method:

@IBAction func textfieldEditingChanged(_ sender: Any) {
    let textfield = sender as! UITextField
    textfield.text = textfield.commaValue
}
Hos Ap
  • 1,168
  • 2
  • 11
  • 24

1 Answers1

0

Solved it temporarily this way:

var formattedNumber: String {
    guard self.text != "" else {return ""}
    var fraction = ""
    var digit = ""

    let fractionExists = self.text!.contains(".")

    let num = self.text?.replacingOccurrences(of: ",", with: "")
    let sections = num!.characters.split(separator: ".")
    if sections.first != nil
    {
        let str = String(sections.first!)
        let double = Double(str)
        guard double != nil else {return self.text ?? ""}
        digit = numberFormatter.string(from: NSNumber(value: double ?? 0))!
    }
    if sections.count > 1
    {
        fraction = String(sections[1])
        if fraction.characters.count > 2
        {
            fraction = String(fraction.prefix(2))
        }
        return "\(digit).\(fraction)"
    }
    if fractionExists
    {
        return "\(digit)."
    }
    return digit
}

.

@IBAction func textfieldEditingChanged(_ sender: Any) {
    let textfield = sender as! UITextField
    textfield.text = textfield.formattedNumber
}
Hos Ap
  • 1,168
  • 2
  • 11
  • 24