ios中textfield中的十进制格式

时间:2013-02-25 09:44:50

标签: ios xcode

我有占位符00.00的文本字段。我想以那种格式输入数字。 请帮忙

2 个答案:

答案 0 :(得分:0)

使键盘类型为数字。并在内部使用下面的代码来获得双重值

      NSString *value =textfield_name.text;
      double doubleValue = [value doubleValue];

答案 1 :(得分:0)

尝试这种方式:

让您的班级成为yourTextField的代表,并添加here使用的代码。

NSString *enteredValue=@"99.129";//get your value from textfield as yourField.text
double doubleValue=[enteredValue doubleValue];
NSString *formattedDoubleValue=[NSString stringWithFormat:@"%.2f",doubleValue];
NSLog(@"->%@",formattedDoubleValue);//now you can set back to the textfield as yourField.text=formattedDoubleValue

或者,您可以使用NSNumberFormatter。

NSNumberFormatter *numFormatter=[NSNumberFormatter new];
[numFormatter setFormat:@"00.00"];
NSString *str=[numFormatter stringFromNumber:@99.129];
NSLog(@"->%@",str);

编辑:根据您的评论

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if (textField == self.yourTextField){
        NSLog(@"here");
        NSString *newString = [textField.text stringByReplacingCharactersInRange:range withString:string];

        NSString *expression = @"^([0-9]{1,2})(\\.([0-9]{1,2})?)?$";

        NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:expression
                                                                               options:NSRegularExpressionCaseInsensitive
                                                                                 error:nil];
        NSUInteger numberOfMatches = [regex numberOfMatchesInString:newString
                                                            options:0
                                                              range:NSMakeRange(0, [newString length])];
        if (numberOfMatches==0){
            return NO;
        }
    }

    return YES;
}
相关问题