vype
vype

Reputation: 221

Convert coordinate string to float

I want to convert a string coordinate with this format 50.3332W to the equivalent float representation -50.3332.

At the moment I have something like this but it just replaces the W character and places the minus sign at the end.

NSString *newtest = [_myTextField.text stringByReplacingOccurrencesOfString:@"W" withString:@"-"];

Any help on this will be helpful.

Upvotes: 1

Views: 197

Answers (2)

Tim007
Tim007

Reputation: 2557

Try this method:

- (float)coordinateToFloat:(NSString*)coordinateString {
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(\\d+\\.?\\d+?)(W)" options:NSRegularExpressionCaseInsensitive error:nil];
    NSString* prefixString = [regex stringByReplacingMatchesInString:coordinateString options:0 range:NSMakeRange(0, coordinateString.length) withTemplate:@"$2$1"];
    NSString* normalizedString = [prefixString stringByReplacingOccurrencesOfString:@"W" withString:@"-"];
    return normalizedString.floatValue;
}

Then, you can call it like this:

[self coordinateToFloat:@"50.3332W"]; // Returns -50.3332
[self coordinateToFloat:@"50.3332"]; // Returns 50.3332

Regex Demo

Upvotes: 1

Dipen Panchasara
Dipen Panchasara

Reputation: 13600

// *** 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);

Upvotes: 1

Related Questions