سؤال

I have a category on NSString with this method:

-(NSNumber *)numberValue
{
    if (!nfStr)
    {
        nfStr = [[NSNumberFormatter alloc] init];
    }

    NSLocale *current = [NSLocale autoupdatingCurrentLocale];

    [nfStr setLocale:current];
    [nfStr setDecimalSeparator:[current objectForKey:NSLocaleDecimalSeparator]];
    [nfStr setGroupingSeparator:[current objectForKey:NSLocaleGroupingSeparator]];

    return [nfStr numberFromString:self];
}

My current locale is it-IT (decimal separator: "," grouping separator: ".")

when I use stringFromNumber with NSNumber 90000 the NumberFormatter return a correctly formatted string "90.000"

when in a textfield I write the string "90.000" the NumberFormatter return nil instead of NSNumber 90000

why?

Thanks

edit: textfield delegate

-(void)textFieldDidEndEditing:(UITextField *)textField
{
  myObject.r.qtaOm = [Trim(textField.text) numberValue];
}
هل كانت مفيدة؟

المحلول

You have to set the NumberStyle on the formatter.

[nfStr setNumberStyle:NSNumberFormatterDecimalStyle];

You can use:

enum {
   NSNumberFormatterNoStyle = kCFNumberFormatterNoStyle,
   NSNumberFormatterDecimalStyle = kCFNumberFormatterDecimalStyle,
   NSNumberFormatterCurrencyStyle = kCFNumberFormatterCurrencyStyle,
   NSNumberFormatterPercentStyle = kCFNumberFormatterPercentStyle,
   NSNumberFormatterScientificStyle = kCFNumberFormatterScientificStyle,
   NSNumberFormatterSpellOutStyle = kCFNumberFormatterSpellOutStyle
};

نصائح أخرى

Lools like your string format is not correctcorrect because numberfromstring method accept string and then returns number but in your case 90.000 is not a valid string it seems So try passing like that and check

 NSString *num=@"90.000"; 

And then check it should work.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top