簡體   English   中英

NSNumberFormatter numberFromString返回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。 始終使用除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 )的類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM