- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
if (string.length == 0) {
return YES;
}
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber* candidateNumber;
NSString* candidateString = [textField.text stringByReplacingCharactersInRange:range withString:string];
range = NSMakeRange(0, [candidateString length]);
[numberFormatter getObjectValue:&candidateNumber forString:candidateString range:&range error:nil];
if (([candidateString length] > 0) && (candidateNumber == nil || range.length < [candidateString length])) {
return NO;
}
else
{
return YES;
}
Hi, with this code i can insert only decimal values in a textfield.
The decimal separator is a comma “,”
How do I change it to a dot “.” ?
Thanks
There is a little thing called
Localization. Every language uses a different character as a decimal separator. Where English uses a decimal point, other languages use a comma (or other characters).When you create a
NSNumberFormatterit uses the system locale (NSLocaleinstance) to decide about the decimal separator (and grouping separator and other things).If you want a fixed behavior, then just set a different locale using
[NSNumberFormatter setLocale:]Also note there is one special kind of locale
[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]which defines a special locale which cannot be changed by user settings and is always the same.In this case, using a
NSNumberFormatteris not the best idea. This is one of the cases when you want to use a regular expression.