将TextField文本格式化为Price

时间:2013-05-22 05:22:18

标签: iphone ios objective-c

我想在用户输入值时格式化文本字段文本..它完美地工作但我的问题是,如果用户在该抽取点之后按1然后按2。我的替换字符串是“12”。那时腰部是12。我无法取小数点。

NSNumber* number = [numberFormatter numberFromString:string];  

这是我的完整代码,

#pragma mark textfieldDelgate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string 
{

  NSLocale *locale=[[NSLocale alloc]initWithLocaleIdentifier:@"en_GB"];

NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:locale];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];

NSString *text = [textField text];
NSString *replacementText = [text stringByReplacingCharactersInRange:range withString:string];
NSMutableString *newReplacement = [[ NSMutableString alloc ] initWithString:replacementText];

NSString *currencyGroupingSeparator = numberFormatter.currencyGroupingSeparator;

[newReplacement replaceOccurrencesOfString:currencyGroupingSeparator withString:@"" options:NSBackwardsSearch range:NSMakeRange(0, [newReplacement length])];






NSNumber * number = [numberFormatter numberFromString:newReplacement];

if (number == nil && [replacementText length]!=0) {

    return NO;
}
NSLog(@"%@",newReplacement);
text = [numberFormatter stringFromNumber:number];
[textField setText:text];
return NO;

  }

我还附上了截图。  如何用十进制值格式化字符串......  提前致谢

4 个答案:

答案 0 :(得分:1)

对我来说代码行:

 NSNumber * number = [numberFormatter numberFromString:newReplacement];

不返回nil但会删除用户输入的小数。这是因为使用numberFormatter id可以传递类似'12'的值。或'12 .0'它将删除小数作为格式的一部分。对于像12.3这样的其他值,它不会删除小数。

我无法理解您执行所有这些编码的要求,但是如果您想要十进制,那么请设置一些逻辑来检查数字的格式是12还是12.0,然后转义格式化。十进制将保留在那里。

请使用此代码:

NSNumber * number;    
if ([newReplacement hasSuffix:@"."] || [newReplacement hasSuffix:@".0"]) 
{ 

 [textField setText:newReplacement]; return NO; 
} 
else 
{ 
 number = [numberFormatter numberFromString:newReplacement]; 
 }

答案 1 :(得分:1)

如果您正在处理格式化资金,您可能希望使用NSNumberFormatterCurrencyStyle代替NSNumberFormatterDecimalStyle。在设置之后它可能是Just Work™。

但是,它可能不会。无论如何,你可以确定你所看到的行为的原因是你没有从你的字符串中给它一个数字; 12是一个数字,12.5也是,但12.不是。我很惊讶它没有完全归还nil

如果是这种情况(并且它仍然没有被破坏),那么你可能想要在最后使用.的特殊情况,而不是将其传递给数字格式化器。

答案 2 :(得分:0)

我已尝试在我的日志中打印您的代码。它对我来说很好。我认为还有其他类型的问题。

NSLocale *locale=[[NSLocale alloc]initWithLocaleIdentifier:@"en_GB"];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setLocale:locale];
[numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber* number = [numberFormatter numberFromString:@"12.4"];

NSLog(@"number is %@",number);

日志打印-----

数字是12.4

答案 3 :(得分:0)

//Add this in .h file

NSNumberFormatter *formatter;
    NSInteger currencyScale;
    NSString *enteredDigits;


//Add this in .m file`enter code here`
-(void)viewdidload
{
  NSNumberFormatter *aFormatter = [[NSNumberFormatter alloc] init];
    [aFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    currencyScale = -1 * [aFormatter maximumFractionDigits];
    self.formatter = aFormatter;
}


#pragma UItextfield Delegate

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    // Keep a pointer to the field, so we can resign it from a toolbar
    Field = textField;
    if(textField.text==NULL || [textField.text isEqualToString:@""])
    {
        self.enteredDigits = @"";
    //textField.text=@"";
    }


}

- (void)textFieldDidEndEditing:(UITextField *)textField {

}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string { //give tag to text field
    if (textField.tag==10) {
        //  self.priceInput = textField;
        // Check the length of the string
        int len=[self.enteredDigits length];
        NSLog(@"string lenght is %d",len);
        if ([string length]) {
            self.enteredDigits = [self.enteredDigits stringByAppendingFormat:@"%d", [string integerValue]];
        } else {
            // This is a backspace
            NSUInteger len = [self.enteredDigits length];
            if (len > 1) {
                self.enteredDigits = [self.enteredDigits substringWithRange:NSMakeRange(0, len - 1)];
            } else {
                self.enteredDigits = @"";
            }
        }

        NSDecimalNumber *decimal = nil;

        if ( ![self.enteredDigits isEqualToString:@""]) {
            decimal = [[NSDecimalNumber decimalNumberWithString:self.enteredDigits] decimalNumberByMultiplyingByPowerOf10:currencyScale];
            float deci= [decimal floatValue];
            NSLog(@"decimall==%f",deci);
        } else {
            decimal = [NSDecimalNumber zero];
        }

        // Replace the text with the localized decimal number
        float deci= [decimal floatValue];
        NSLog(@"decimall==%f",deci);
        NSString *temp = [self.formatter stringFromNumber:decimal];
        textField.text=temp;
            //NSLog(@"Text fielddddddddddddddf=%@ %@",numberText,temp);

        return NO;  
    }




    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    textField.text=@"";
    self.enteredDigits=@"";
    NSLog(@"Clear Clicked");
    return YES;

}



I think this code will help you