NSNumberFormatter numberFromString返回null

时间:2011-12-06 15:13:00

标签: iphone objective-c ios nsnumber nsnumberformatter

这是我的代码

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];

1 个答案:

答案 0 :(得分:6)

什么是price?假设它是一个ivar,不要直接访问ivars。始终使用除deallocinit之外的访问者。

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

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

如果priceNSNumber,那么您可以直接使用它。

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

并且一直到你的实际问题,原因金额是nil是因为“5”不是当前的货币格式,所以数字格式化程序拒绝它。如果您在美国并将price设置为“$ 5.00”,那么它可以正常工作。


如果你真的想把字符串转换成美元,那么这就是怎么做的。请注意,语言环境很重要。如果您使用默认语言环境,那么在法国“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);

iOS 5 Programming Pushing the Limits第13章的示例代码中提供了一个更完整的用于管理本地化货币(RNMoney)的类。