Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit the textfield entry to 2 decimal places in swift 4?

Tags:

ios

swift

I have a textfield and I want to limit the entry to max 2 decimal places.

number like 12.34 is allowed but not 12.345

How do I do it?

like image 707
KawaiKx Avatar asked Aug 01 '17 16:08

KawaiKx


People also ask

How do I limit two decimal places in Swift?

By using round(_:) , ceil(_:) , and floor(_:) you can round Double and Float values to any number of decimal places in Swift.

How do you limit decimal places to 2?

Rounding a decimal number to two decimal places is the same as rounding it to the hundredths place, which is the second place to the right of the decimal point. For example, 2.83620364 can be round to two decimal places as 2.84, and 0.7035 can be round to two decimal places as 0.70.

How do you set a field's decimal places in Design view?

Press TAB, open the drop-down menu, and choose Number. Click in the Field Size property, open the drop-down menu, and choose Single. Press TAB, open the drop-down menu, and choose Fixed. Click in the Decimal Places property.


2 Answers

Set your controller as the delegate for the text field and check if the proposed string satisfy your requirements:

override func viewDidLoad() {
    super.viewDidLoad()
    textField.delegate = self
    textField.keyboardType = .decimalPad
}

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    guard let oldText = textField.text, let r = Range(range, in: oldText) else {
        return true
    }

    let newText = oldText.replacingCharacters(in: r, with: string)
    let isNumeric = newText.isEmpty || (Double(newText) != nil)
    let numberOfDots = newText.components(separatedBy: ".").count - 1

    let numberOfDecimalDigits: Int
    if let dotIndex = newText.index(of: ".") {
        numberOfDecimalDigits = newText.distance(from: dotIndex, to: newText.endIndex) - 1
    } else {
        numberOfDecimalDigits = 0
    }

    return isNumeric && numberOfDots <= 1 && numberOfDecimalDigits <= 2
}
like image 179
Code Different Avatar answered Oct 13 '22 09:10

Code Different


Guys, here's the solution:

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let dotString = "."

        if let text = textField.text {
            let isDeleteKey = string.isEmpty

            if !isDeleteKey {
                if text.contains(dotString) {
                    if text.components(separatedBy: dotString)[1].count == 2 {

                                return false

                    }

                }

            }
        }
  }
like image 25
Mihail Salari Avatar answered Oct 13 '22 09:10

Mihail Salari