我想将具有此格式50.3332W
的字符串坐标转换为等效的浮点表示-50.3332
。
目前我有这样的事情,但它只是替换了W
字符,并在最后放置了减号。
NSString *newtest = [_myTextField.text stringByReplacingOccurrencesOfString:@"W" withString:@"-"];
任何有关此方面的帮助都会有所帮助。
答案 0 :(得分:1)
// *** Your string value ***
NSString *value = @"50.3332W";
// *** Remove `W` from string , convert it to float and make it negative by multiplying with -1.
CGFloat floatValue = [[value stringByReplacingOccurrencesOfString:@"W" withString:@""] floatValue] * -1;
// ** Result negative float value without `W` **
NSLog(@"%f",floatValue);
答案 1 :(得分:1)
试试这个方法:
- (float)coordinateToFloat:(NSString*)coordinateString {
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d+\\.?\\d+?)(W)" options:NSRegularExpressionCaseInsensitive error:nil];
NSString* preffixString = [regex stringByReplacingMatchesInString:coordinateString options:0 range:NSMakeRange(0, coordinateString.length) withTemplate:@"$2$1"];
NSString* normalizedString = [preffixString stringByReplacingOccurrencesOfString:@"W" withString:@"-"];
return normalizedString.floatValue;
}
然后,您可以这样称呼它:
[self coordinateToFloat:@"50.3332W"]; // Returns -50.3332
[self coordinateToFloat:@"50.3332"]; // Returns 50.3332