I have a set of objects where one property is a float value like 36.6 or 19.9. Given a value such as 34.6, how would I design a predicate to fetch only those objects whose NSNumber float values of this property round to 34.6?
Normally I would do a test like:
if(value - test <= .01 && test - value <= .01) { //they match }
But how would you do this inside a predicate? The predicate doesn't seem to have the ability to do basic arithmetic inside of itself, or to test two float values for equivalency, am I right? Isn't it bad to try to see if two float values are the same? Or does the predicate search know that it's comparing two floats and only do it with a reasonable degree of precision?
This should work:
float test = 34.6;
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"value >= %f AND value <= %f",
test - 0.01, test + 0.01];
Update: Actually you can do some arithmetic in a Core Data predicate. The following predicate works as well:
[NSPredicate predicateWithFormat:@"abs(value - %f) < 0.01", test];
According to http://www.sqlite.org/datatype3.html, all real numbers are stored as an 8-byte IEEE floating point number in the SQLite database. Therefore numbers like 36.6 or 19.9 cannot be stored exactly, and comparing with some tolerance (probably less that 0.01) is the right way to go.