[英]What is __AVAILABILITY_INTERNAL__IPHONE_2, NS_AVAILABLE ? Trying to use NSNumberFormatter, returns (null)
[英]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,不要直接访问ivars。 始终使用除dealloc
和init
。
假设price
是一个字符串,你为什么这样做:
[NSString stringWithFormat:@"%@", price]
如果price
是NSNumber
,那么您可以直接使用它。
你在这里创建一个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
)的类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.