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 mark
e.g.
2.5 OK
2..5 NOT OK
Select the cell with a number (B2) and in the Ribbon, go to Home > Number Format. 2. In the Format Cells window, enter the number of decimal places (for example, 3) and click OK. You can immediately see how the number will look in the Sample box.
Select the cells you want to format. On the Home tab, select Increase Decimal or Decrease Decimal to show more or fewer digits after the decimal point. Each selection or click adds or removes a decimal place.
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.
The C++ setprecision can also be used to format only the decimal places instead of the whole floating-point or double value. This can be done using the fixed keyword before the setprecision() method.
Implement the shouldChangeCharactersInRange method like this:
// Only allow one decimal point // Example assumes ARC - Implement proper memory management if not using. - (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string]; NSArray *arrayOfString = [newString componentsSeparatedByString:@"."]; if ([arrayOfString count] > 2 ) return NO; return YES; }
This creates an array of strings split by the decimal point, so if there is more than one decimal point we will have at least 3 elements in the array.
Here is an example with a regular expression, the example limits to only one decimal point and 2 decimals. You can tweak it to fit your needs.
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string]; NSString *expression = @"^[0-9]*((\\.|,)[0-9]{0,2})?$"; NSError *error = nil; NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression options:NSRegularExpressionCaseInsensitive error:&error]; NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString options:0 range:NSMakeRange(0, [newString length])]; return numberOfMatches != 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With