How to set the text box format as decimal when typing?

In my application, I have one text field, and when I click on this text field, a numeric keypad will open. Now my question is how to convert this value to decimal format as I type, since I need to insert only decimal values ​​and dot (.) Is not indicated in the numeric keypad. When the user enters a text field, he automatically converts this value to decimal format.

Suppose a custom type 5078 displays a 50.78 format when entering text.

+4
source share
3 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 the textField:shouldChangeCharactersInRange:withString: method textField:shouldChangeCharactersInRange:withString:

 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; 
+7
source

try it.

  -(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; } 
+3
source

Thanks, it works great. In my case, I need to format the decimal point as a localized currency format when finish editing.

 - (BOOL) textFieldShouldEndEditing:(UITextField *)textField { NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; formatter.numberStyle = NSNumberFormatterCurrencyStyle; // im my case i need specify the currency code, // but could have got it from the system. formatter.currencyCode = @"BRL"; NSDecimalNumber *decimalNumber = [NSDecimalNumber decimalNumberWithString:textField.text]; // keeping the decimal value for submit to server. self.decimalValue = decimalNumber; // formatting to currency string. NSString * currencyString = [formatter stringFromNumber:decimalNumber]; textField.text = currencyString; 

}

0
source

All Articles