Question

I'm adding a bunch of coordinates into quad tree and when I'm asking for the closest coordinate near my location, sometimes I've coordinate with 0 at the end, added automatically perhaps by the quad tree or I don't know how. The problem is when I'm asking the double value in my core data using predicate it won't match because of the 0 digit addition to the number.

I thought about removing it when I've 0 but I'm sure there is a better way doing it.

For example:

  • Near location 31.123456, 34.123456, the nearest is 31.123444, 34.123450 when '34.123450' is actually 34.12345 in the database.
Was it helpful?

Solution

//Convert float to String

NSString *str_lat = @"34.123450";


NSString *trimmedString=[str_lat substringFromIndex:MAX((int)[str_lat length]-1, 0)];

if([trimmedString isEqualToString:@"0"])
{
    str_lat = [str_lat substringToIndex:[str_lat length] - 1];
}
else
{

}
NSLog(@"%@",str_lat);

OTHER TIPS

First: You should not store numbers as strings. 7.3 and 7.30 are the same values with simply different representations. You should not compare the representations, but the value.

Second: You should not compare floating-point numbers with == but their difference to a delta. In a calculation precision might get lost, rounding is applied and so on. The "mathematical" equal values might be physical different by a more or less small amount.

// remove the zeros from values (if you have them as floats)
NSString *valueFromTheDataBase = [NSString stringWithFormat:@"%g", 34.123450];
NSString *yourValue  = [NSString stringWithFormat:@"%g", 34.12345];

if([yourValue isEqualToString:valueFromDataBase]) {
// they are equal
}

OR Make Them floats and compare them

// make them floats and compare them
CGFloat floatFromDB = [valueFromDB floatValue];
CGFloat yourFloat  = [yourString floatValue];
if((floatFromDB - yourFloat) == 0) {
// they are equal
}

UPDATED as @Amin Negm says

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top