我試圖以從貨幣樣式設置格式的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,我試圖在最初的帖子中測試...)。編碼問題?
您可以顯示您正在創建的'NSLog'調用嗎? – PengOne
這段代碼對我來說工作得很好。你是如何調試它的?我正在使用NSLog(「%f」,amountDouble); –
我相信問題在於$符號。由於你的字符串有符號,當試圖獲得該符號的雙倍值時,它會給出一個大的0. –