Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting user input to a valid decimal number in Swift

I have found a lot of guides on how to do this in objective-c, but I would like to see a more Swift-oriented way of doing this.

I have a UITextField that a user enters a currency price into. The textfield calls a decimal pad keyboard. However, on the iPad, the keyboard that comes up has a whole range of non-decimal symbols.

Basically, for every single key press, I would like to make it impossible for a non-number or anything beyond a single decimal to be typed into the field. If a decimal is typed, I would like to make it impossible to enter a second decimal. If the decimal is deleted, I'd like to make sure the user can enter a decimal again.

Any ideas on how to properly do this in swift?

I also see solutions like the ones posted here: Limit UITextField to one decimal point Swift But I have no idea where to place the functions or how I should call them. Whenever I try to put in NSRange in the parameters, I receive an error that I am not creating a range properly.

like image 233
Gabriel Garrett Avatar asked Oct 25 '14 20:10

Gabriel Garrett


People also ask

How do I restrict the number of decimal places?

Now you can limit the decimal places. Select the number cell and in the Menu, go to Format > Number > More Formats > Custom number format.

How do you round to 2 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.

Can we store decimal values in int?

Unless you really need to save those bytes, I wouldn't recommend you do this as it's usually better to store the full precision. However, this does show that we can store decimals in integer data types with a bit of math involved.

Can we store decimal values in number data type?

The Decimal data type provides the greatest number of significant digits for a number. It supports up to 29 significant digits and can represent values in excess of 7.9228 x 10^28. It is particularly suitable for calculations, such as financial, that require a large number of digits but cannot tolerate rounding errors.


2 Answers

Swift 4.2

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let numberCharSet = CharacterSet(charactersIn: ".").union(CharacterSet.decimalDigits)
    let characterSet = CharacterSet(charactersIn: string)
    return numberCharSet.isSuperset(of: characterSet)
}

This allows digits from 0 to 9 and decimal point .

like image 111
Abhishek Jain Avatar answered Oct 11 '22 14:10

Abhishek Jain


Swift 3 Implement this UITextFieldDelegate method to prevent user from typing an invalid number:

func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    let text = (textField.text ?? "") as NSString
    let newText = text.replacingCharacters(in: range, with: string)
    if let regex = try? NSRegularExpression(pattern: "^[0-9]*((\\.|,)[0-9]{0,2})?$", options: .caseInsensitive) {
        return regex.numberOfMatches(in: newText, options: .reportProgress, range: NSRange(location: 0, length: (newText as NSString).length)) > 0
    }
    return false
}

It is working with both comma or dot as decimal separator and allows 2 fraction digits.

like image 32
Miroslav Hrivik Avatar answered Oct 11 '22 14:10

Miroslav Hrivik