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.
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;
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;
}
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