2011-11-22 34 views
0

我試圖以從貨幣樣式設置格式的UITextField(例如:$ 30,034.12 => 30034.12):獲得雙值來測試下面的代碼NSNumberFormatter numberFromString貨幣風格格式化返回0

// Init and configure formatter 
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init]; 
[formatter setNumberStyle:NSNumberFormatterCurrencyStyle]; 
[formatter setMaximumFractionDigits:2]; 
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"us_US"]; 
[formatter setLocale:locale]; 
[formatter setGroupingSize:3]; 
[formatter setUsesGroupingSeparator:YES]; 
[formatter setGroupingSeparator:@","]; 
[formatter setAllowsFloats:YES]; 

// Get a formatted string using the local currency formatter and then get a double 
// vice-versa 
NSNumber *amount = [NSNumber numberWithDouble:30034.12]; 

NSString *amountString = [formatter stringFromNumber:amount]; 
// Output here OK : @"$ 30,034.12" 

double amountDouble = [[formatter numberFromString:amountString] doubleValue]; 
// Output here NOT OK : 0 

難道任何人都有/解決了同樣的問題?

謝謝!

更新:

@DanielBarden和其他人。實際上,爲了簡化這篇文章,我沒有包含指定我從哪裏獲取字符串的部分:文本字段。實際上,代碼的結束之前的線應爲:

// Init fromatter with style $ XXX,XXX.yy 
    NSNumberFormatter* formatter = [[NSNumberFormatter alloc] init]; 
    [formatter setNumberStyle:NSNumberFormatterCurrencyStyle]; 
    [formatter setMaximumFractionDigits:2]; 
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"us_US"]; 
    [formatter setLocale:locale]; 
    [formatter setGroupingSize:3]; 
    [formatter setGroupingSeparator:@","]; 
    [formatter setUsesGroupingSeparator:YES]; 

    // Get the float value of the text field and format it 
    textField.text = [formatter 
         stringFromNumber:[NSNumber 
             numberWithDouble:[textField.text 
                 floatValue]]]; 

NSString *amountString = [textField text]; 

而這個文本字段以前與來自另一方法如下代碼格式化(使用相同的格式配置貨幣樣式)

現在的問題是,當我做一個NSLog時,我得到完全相同的字符串,但是當我通過字符與一個循環比較它們時,它表示$後面的空格是文本字段上的「真實空間」,並且不同符號在最初的字符串(amountString,我試圖在最初的帖子中測試...)。編碼問題?

+0

您可以顯示您正在創建的'NSLog'調用嗎? – PengOne

+1

這段代碼對我來說工作得很好。你是如何調試它的?我正在使用NSLog(「%f」,amountDouble); –

+0

我相信問題在於$符號。由於你的字符串有符號,當試圖獲得該符號的雙倍值時,它會給出一個大的0. –

回答

0

該代碼對我來說看起來是正確的,Xcode與我同意。我在兩行中添加了你缺少的內容:

NSLog(@"%@",amountString); 
NSLog(@"%f",amountDouble); 

並且輸出是正確的。我建議你檢查你如何記錄數值。

+0

是的,實際上這個代碼工作正常,它沒有出現在我包括原始代碼,我從文本字段中獲取數量字符串。這個double以前使用相同的格式化程序格式化並影響到文本字段。從那裏我試圖以另一種方式來完成這項任務。 我在「Update:」下的原始文章末尾添加了有關該問題的更詳細說明。我懷疑一個編碼問題,但仍然在努力。你有什麼線索?非常感謝 ! –

0

我能想到的唯一的問題是$符號的問題。將格式化程序設置爲貨幣形式需要$符號,如果它不存在於字符串中,它將返回0

+0

嗯......當我試圖更深入地調試它時,我意識到我實際上遇到了將$符號與數值分開的空間問題。我懷疑編碼問題,但仍然沒有解決它。我在原帖的末尾添加了更詳細的解釋,以備有時間閱讀。非常感謝 ! –