Objective-C - float checking for nan

Objective CFloating PointNan

Objective C Problem Overview


I have a variable float slope that sometimes will have a value of nan when printed out since a division by 0 sometimes happens.

I am trying to do an if-else for when that happens. How can I do that? if (slope == nan) doesn't seem to work.

Objective C Solutions


Solution 1 - Objective C

Two ways, which are more or less equivalent:

if (slope != slope) {
    // handle nan here
}

Or

#include <math.h>
...
if (isnan(slope)) {
    // handle nan here
}

(man isnan will give you more information, or you can read all about it in the C standard)

Alternatively, you could detect that the denominator is zero before you do the divide (or use atan2 if you're just going to end up using atan on the slope instead of doing some other computation).

Solution 2 - Objective C

Nothing is equal to NaN — including NaN itself. So check x != x.

Solution 3 - Objective C

 if(isnan(slope)) {
    
     yourtextfield.text = @"";
     //so textfield value will be empty string if floatvalue is nan
}
else
{
     yourtextfield.text = [NSString stringWithFormat:@"%.1f",slope];
}

Hope this will work for you.

Solution 4 - Objective C

In Swift, you need to do slope.isNaN to check whether it is a NaN.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionteepusinkView Question on Stackoverflow
Solution 1 - Objective CStephen CanonView Answer on Stackoverflow
Solution 2 - Objective CChuckView Answer on Stackoverflow
Solution 3 - Objective CAswathy BoseView Answer on Stackoverflow
Solution 4 - Objective CZhaoView Answer on Stackoverflow