I am fetching a latitude and longitude from a JSON API. These values are coming in as Strings.
I store the value in a CLLocationDegrees
like this:
CLLocationDegrees lat = [[coordinates objectForKey:@"lat"] doubleValue];
CLLocationDegrees lon = [[coordinates objectForKey:@"lat"] doubleValue];
But when I later retrieve the values from lat
and lon
and put them into an NSString
, the value has changed from what was provided by the JSON. The change is usually only the last few digits of the coordinate, but it is enough to cause a problem.
NSString *latitude = [[NSNumber numberWithDouble:lat] stringValue];
NSString *longitude = [[NSNumber numberWithDouble:lon] stringValue];
Basically, at this point, [coordinates objectForKey:@"lat"]
is not equal to latitude
.
Any tips about how to fix this would be appreciated
NSNumber stringValue
is going to give you a default representation which generally only has 5 decimal places.
One option would to use stringWithFormat
and use a format that matches the data you have from the original JSON.
NSString *latitude = [NSString stringWithFormat:@"%.7f", lat];
Adjust the format specifier to meet your exact needs.
Also keep in mind that going from the original string to a double
could result in some loss of precision due to the nature of how floating point numbers are represented. There's nothing you can do about that except keep a reference to the original string if it is that important.