Search code examples
iosobjective-cuilabelcalculator

Prevent Users from Entering Multiple Decimals In Objective-C


I am making an only number input app (still) in which users press a button, I store a value into a string to display in a label.

Works great for the most part, except I cannot figure out how to prevent users from entering more than one decimal in a single string. .

I looked at this Stack overflow question, but trying to amend the code for my own just resulted in a whole bunch of errors. Does anyone have any advice?

- (void)numberBtn:(UIButton *)sender {
    if (self.sales.text.length < 10) {
        if(self.sales.text.length != 0){
            NSString *lastChar = [self.sales.text substringFromIndex:[self.sales.text length] - 1];
            
            if([lastChar isEqualToString:@"."] && [sender.titleLabel.text isEqualToString:@"."] && [sender.titleLabel.text stringByAppendingString:@"."]){
                return;   
            }
            
            if ([lastChar isEqualToString:@""] && [sender.titleLabel.text isEqualToString:@""]){
                self.numbers = @"0.";
            }
            if ([self.sales.text rangeOfString:@"."].length > 0) {
                NSArray *array = [self.sales.text componentsSeparatedByString:@"."];
                if (array.count == 2) {
                    NSString *decimal = array.lastObject;
                    if (decimal.length > 2) {
                        return;
                    }
                }
            }
        }
        
        self.numbers = [NSString stringWithFormat:@"%@%@",self.numbers,sender.titleLabel.text];
        self.sales.text = self.numbers;
    }
}

Solution

  • Two steps...

    • Check to see if the button is a decimal .
    • if yes, see if the current label text already contains a .

    If it does, return. If not, continue processing your button input:

    - (void)numberBtn:(UIButton *)sender {
        NSString *btnTitle = sender.currentTitle;
        NSString *curText = self.sales.text;
        if ([btnTitle isEqualToString:@"."]) {
            if ([curText containsString:@"."]) {
                NSLog(@"%@ : Already has a decimal point!", curText);
                return;
            }
        }
        // whatever else you want to do with the input...
    }