我尝试测试以下代码以从货币样式格式化的 UITextField 中获取双精度值(例如:$ 30,034.12 => 30034.12):
// 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 和其他人。实际上,为了简化帖子,我没有包含指定从何处获取字符串的部分:文本字段。实际上,代码末尾之前的行应该是:
NSString *amountString = [textField text];
并且此文本字段先前已使用另一种方法的以下代码格式化(货币样式使用相同的格式化程序配置):
// 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]]];
现在的问题是,当我执行 NSLog 时,我得到完全相同的字符串,但是当我将它们逐个字符与循环进行比较时,它表示 $ 之后的空格是文本字段上的“真实空间”,而不同的符号初始字符串(amountString 我在最初的帖子中尝试测试的那个...)。编码问题?