I want to limit the digits entered in UITextField. Here is my code
#define MAX_NO_OF_DIGITS_BEFORE_DECIMAL 8
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
switch (textField.tag)
{
case BUY_ITEM_TEXTFIELD_TAG:
{
if (![textField.text length]>0) {
textField.text = [CURRENCY_TYPE stringByAppendingFormat:@"%@",self.buyTextField.text];
}
}
break;
case BID_INCREMENT_TEXTFIELD_TAG:
{
if (![textField.text length]>0) {
textField.text = [CURRENCY_TYPE stringByAppendingFormat:@"%@",self.bidTextField.text];
}
}
break;
case STARTING_BID_TEXTFIELD_TAG:
{
if (![textField.text length]>0) {
textField.text = [CURRENCY_TYPE stringByAppendingFormat:@"%@",self.startingBidTextField.text];
}
}
break;
case SHIPPING_CHARGES_TEXTFILED:
{
if (![textField.text length]>0) {
textField.text = [CURRENCY_TYPE stringByAppendingFormat:@"%@",self.chargesTextField.text];
}
}
break;
default:
break;
}
NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];
// Check if we have 8 digits before decimal points
NSString *tempStr = [newString stringByReplacingOccurrencesOfString:CURRENCY_TYPE withString:@""];
if ([tempStr length]==MAX_NO_OF_DIGITS_BEFORE_DECIMAL)
{
// Check if we have only 1 decimal point
NSArray *arrayOfString = [newString componentsSeparatedByString:@"."];
if ([arrayOfString count] > 2 )
{
return NO;
}
else {
textField.text = [NSString stringWithFormat:@"%@%@%@",CURRENCY_TYPE,tempStr,@"."];
}
}
// Check if we have only 1 decimal point
NSArray *arrayOfString = [newString componentsSeparatedByString:@"."];
if ([arrayOfString count] > 2 )
{
return NO;
}
// Check if we have only 2 digits after decimal point
if([arrayOfString count]>=2)
{
NSString *sepStr=[NSString stringWithFormat:@"%@",[arrayOfString objectAtIndex:1]];
return !([sepStr length]>2);
}
return YES;
}
But my problem is when I enter 12345678 , it places decimal point after 8 & again places 8 so my output is looks like 12345678.8
instead of 12345678.
What I want to achieve is
1) User can enter only MAX_NO_OF_DIGITS_BEFORE_DECIMAL before decimal & 2 digits after decimal
I can't understand why last 8 gets repeated in this. Can anybody help me ?
Thanks in advance.
First, add logging to each step to view what happens, or debug.
The problem is that you are modifying the string (to create the newString variable). Then you are adding the period to the end and setting this as the new value of the text field. Then you are returning yes (your latter checks don't use the new text field value). So you add the '8' and the period, and then ask the framework to add the '8'.