我无法理解为什么我会得到以下结果,我们将不胜感激。
NSString *amountString =@"9,376.41";
double amount = [amountString doubleValue];
NSLog(@"My Amount %f",amount);
My Amount 9.000000
答案 0 :(得分:2)
在处理与字符串之间转换数字时,应始终使用正确配置的NSNumberFormatter
NSString *amountString = @"9,376.41";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *amount = [formatter numberFromString:amountString];
NSLog(@"My Amount %@", amount);
您可以设置区域设置/格式以处理不同的千位分隔符等
答案 1 :(得分:1)
使用stringByReplacingOccurrencesOfString取出逗号,它可以正常工作
NSString *amountString =@"9,568,376.41";
NSString *outString = [amountString stringByReplacingOccurrencesOfString:@"," withString:@""];
double amount = [outString doubleValue];
NSLog(@"My Amount %f",amount);
My Amount 9568376.410000