可能有更简单的方法..但这应该有效..
NSString *originalString = @"23.0984 USD";
NSString *numberString = [originalString stringByReplacingOccurrencesOfString:@" USD"
withString:@""];
float number = [numberString floatValue];
NSString *changedString = [NSString stringWithFormat:@"%.2f",number];
NSLog(@"ChangedString : %@ USD",changedString);
编辑:这个答案已经被接受。但我认为从字符串中获取数字的更好方法是搜索空格而不是替换硬编码字符串@" USD"。
NSString *originalString = @"23.0984 USD";
NSString *numberString = nil;
NSArray *parts = [originalString componentsSeparatedByString:@" "]; //space
if(parts && [parts lenght]){
numberString = [parts objectAtIndex:0];
}
float number = [numberString floatValue];
NSString *changedString = [NSString stringWithFormat:@"%.2f",number];
NSLog(@"ChangedString : %@ USD",changedString);