Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the textfield format as decimal while typing?

In my app i have one text field and when i click on that text field numeric keypad will open.now my question is how to convert that value in decimal format while typing as i have to insert only decimal values and in numeric keypad dot(.)is not given.so when user type in textfield it automatically convert that value into decimal format.

Suppose if user type 5078 it will show 50.78 format while typing.

like image 344
Developer Avatar asked Dec 21 '22 08:12

Developer


2 Answers

You can simply multiply the number by "0.01" (for two decimal places) and use the string format "%.2lf". Write the following code in textField:shouldChangeCharactersInRange:withString: method.

NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
text = [text stringByReplacingOccurrencesOfString:@"." withString:@""];
double number = [text intValue] * 0.01;
textField.text = [NSString stringWithFormat:@"%.2lf", number];
return NO;
like image 96
EmptyStack Avatar answered Jan 19 '23 21:01

EmptyStack


try this.

 -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
    replacementString:(NSString *)string {

    double currentValue = [textField.text doubleValue];
    double cents = round(currentValue * 100.0f);

    if ([string length]) {
        for (size_t i = 0; i < [string length]; i++) {
            unichar c = [string characterAtIndex:i];
            if (isnumber(c)) {
                cents *= 10;
                cents += c - '0'; 
            }            
        }
    } else {
        // back Space
        cents = floor(cents / 10);
    }

    textField.text = [NSString stringWithFormat:@"%.2f", cents / 100.0f];
     if(cents==0)
    {
        textField.text=@"";
        return YES;
    }
    return NO;
    }
like image 31
Arun Avatar answered Jan 19 '23 21:01

Arun