3

这是我的代码

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

1 回答 1

6

是什么price?假设它是 ivar,请不要直接访问 ivar。始终使用除 indealloc和之外的访问器init

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

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

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

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

一直到您的实际问题,原因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);

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

于 2011-12-06T15:28:51.690 回答