我相信有更有效的方法,但你可以:
NSArray *strings = @[@"¥1,234",@"AU$3,456.78",@"56.78€"];
NSCharacterSet *nonNumbersSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789."] invertedSet];
for (NSString *string in strings)
{
NSString *result = [string stringByTrimmingCharactersInSet:nonNumbersSet];
result = [result stringByReplacingOccurrencesOfString:@"," withString:@""];
CGFloat floatResult = [result floatValue];
NSLog(@"%@ -> %.2f", result, floatResult);
}
或者,您可以使用扫描仪:
NSArray *strings = @[@"¥1,234",@"AU$3,456.78",@"56.78€"];
NSCharacterSet *numbersSet = [NSCharacterSet characterSetWithCharactersInString:@"0123456789.,"];
for (NSString *string in strings)
{
NSString *result;
NSScanner *scanner = [NSScanner scannerWithString:string];
[scanner scanUpToCharactersFromSet:numbersSet intoString:nil];
[scanner scanCharactersFromSet:numbersSet intoString:&result];
result = [result stringByReplacingOccurrencesOfString:@"," withString:@""];
CGFloat floatResult = [result floatValue];
NSLog(@"%@ -> %.2f", result, floatResult);
}
当然,这些假设数字使用逗号作为千位分隔符。
您还可以使用NSNumberFormatter
:
NSArray *strings = @[@"¥1,234",@"AU$3,456.78",@"56.78€"];
NSCharacterSet *nonNumbersSet = [[NSCharacterSet characterSetWithCharactersInString:@"0123456789.,"] invertedSet];
for (NSString *string in strings)
{
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
NSString *result = [string stringByTrimmingCharactersInSet:nonNumbersSet];
NSNumber *numberResult = [formatter numberFromString:result];
NSLog(@"%@ -> %.2f", result, [numberResult floatValue]);
}