objective-cfloating-pointcomparisonprecisionconvenience-methods

What is the convenience method to compare two NSNumbers with float values using limited precision?


What is the Objective-C convenience method for comparing a couple of NSNumbers with float values to see if they are roughly equivalent (two decimal places of precision is fine)?

I would use something other than floats if there was an option that did not change the number around randomly. But anyway I'm already using floats so... .

I imagine there must be something like:

[myNumber isEqualTo:myOtherNumber withPrecision:2];

But actually, amazingly I can't find such a convenience method. What am I missing here?

Would it help to cast the two numbers to NSDecimal or something?


Solution

  • return (fabs([myNumber doubleValue] - [myOtherNumber doubleValue]) < 0.01);
    

    My objective-c is a little rusty, but putting this in a method that accepts to NSNumbers and returns a bool should work.