1

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?

CommaToast
  • 11,370
  • 7
  • 54
  • 69
  • Pseudo-code version looks like this: `( abs(num1 - num2) < 0.01 )`. This evaluates to true if the difference between them is less than one-onehundredth (which is 2 decimal points of precision), and false otherwise. – nhgrif Sep 30 '13 at 02:03
  • There is no convenience method because there is no general rule for comparing floating point numbers with a tolerance. The proper comparison is application-dependent. – Eric Postpischil Sep 30 '13 at 10:53

1 Answers1

2
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.

nhgrif
  • 61,578
  • 25
  • 134
  • 173