NSNumberFormatter numberFromString returns null



这是我的代码

NSNumberFormatter *currencyStyle = [[NSNumberFormatter alloc] init];
    [currencyStyle setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [currencyStyle setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber *amount = [[NSNumber alloc] init];
    NSLog(@"the price string is %@", price);
    amount = [currencyStyle numberFromString:price];
    NSLog(@"The converted number is %@",[currencyStyle numberFromString:price]);
    NSLog(@"The NSNumber is %@", amount);
    NSLog(@"The formatted version is %@", [currencyStyle stringFromNumber:amount]);
    NSLog(@"--------------------");
    self.priceLabel.text = [currencyStyle stringFromNumber:amount]; 
    [amount release];
    [currencyStyle release];

这是日志吐出的

的价格字符串是5转换后的数字为(null)NSNumber是(null)格式化版本为(null)

我错过了什么吗?

编辑:更新代码

NSNumberFormatter *currencyStyle = [[NSNumberFormatter alloc] init];
    [currencyStyle setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [currencyStyle setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber *amount = [currencyStyle numberFromString:price];
    NSLog(@"the price string is %@", price);
    NSLog(@"The converted number is %@",[currencyStyle numberFromString:price]);
    NSLog(@"The NSNumber is %@", amount);
    NSLog(@"The formatted version is %@", [currencyStyle stringFromNumber:amount]);
    NSLog(@"--------------------");
    self.priceLabel.text = [NSString stringWithFormat:@" %@ ", [currencyStyle stringFromNumber:amount]]; 
    [currencyStyle release];

什么是price ?假设它是ivar,不要直接访问ivar。除deallocinit外,始终使用访问器

假设price是一个字符串,为什么要这样做:

[NSString stringWithFormat:@"%@", price]

如果price是一个NSNumber,那么你可以直接使用它。

您在这里创建了NSNumber,将其分配给amount,然后立即将其丢弃。然后过度释放amount。所以你应该预料到上面的代码会崩溃。(由于NSNumber对象的管理方式很奇怪,下次为整数5创建NSNumber时会发生这种崩溃。)

回到你的实际问题,amount是nil的原因是因为"5"不是当前的货币格式,所以数字格式化器拒绝了它。如果你在美国,并将price设置为"$5.00",那么它就可以工作了。


如果你真的想把一个字符串转换成US$,那么就应该这样做。注意,这里的语言环境很重要。如果您使用默认语言环境,那么在法国"1.25"将是€1.25,这与$1.25不同。

当你持有货币时,你应该始终使用NSDecimalNumber。否则,您将受到二进制/十进制舍入错误的影响。

下面使用ARC。

NSString *amountString = @"5.25";
NSDecimalNumber *amountNumber = [NSDecimalNumber decimalNumberWithString:amountString];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSNumberFormatter *currencyStyle = [[NSNumberFormatter alloc] init];    
[currencyStyle setNumberStyle:NSNumberFormatterCurrencyStyle];
[currencyStyle setLocale:locale];
NSString *currency = [currencyStyle stringFromNumber:amountNumber];
NSLog(@"%@", currency);

一个更完整的管理本地化货币的类(RNMoney)可以在iOS 5 Programming Pushing the Limits第13章的示例代码中找到。

最新更新