How can I limit the number of decimal points in a UITextField?

后端 未结 15 2253
说谎
说谎 2020-12-01 05:20

I have a UITextField that when clicked brings up a number pad with a decimal point in the bottom left. I am trying to limit the field so that a user can only place 1 decimal

相关标签:
15条回答
  • 2020-12-01 06:09

    Short told, the number format is as follows [NSString stringWithFormat:@"%9.5f", x]; Where 5 is the decimal after ",".

    0 讨论(0)
  • 2020-12-01 06:10

    For Swift 2.3 to prevent user for enter decimal number after two places -

    func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool
    {
        let decimalPlacesLimit = 2
        let rangeDot = txtPrice.text!.rangeOfString(".", options: .CaseInsensitiveSearch)
    
        if rangeDot?.count > 0
        {
            if (string == ".")
            {
                print("textField already contains a separator")
                return false
            }
            else {
    
                var explodedString = txtPrice.text!.componentsSeparatedByString(".")
                let decimalPart = explodedString[1]
                if decimalPart.characters.count >= decimalPlacesLimit && !(string == "")
                {
                    print("textField already contains \(decimalPlacesLimit) decimal places")
                    return false
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-01 06:13
    -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
    {
        if(textField == min_textfield )
        {
            if([textField.text rangeOfString:@"."].location == NSNotFound)
            {
                if([string isEqualToString:@"."] )
                {
                    flag_for_text = 1;
                }
                else 
                {
                    textField.text = [NSMutableString stringWithFormat:@"%@",textField.text];
                }
            }
            else 
            {
                if([string isEqualToString:@"."])
                {
                    return NO;
                }
                else 
                {
                    textField.text = [NSMutableString stringWithFormat:@"%@",textField.text];
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题