How to catch a Nan?

How to catch a Nan?

NaN is not equal to any value, including NaN, use this property instead of the equal-to operator (==) or not-equal-to operator (!=) to test whether a value is or is not NaN.

 

Nan represents Not a number

When it happens to get a Nan as a result of an expression you have to find a way to catch it before.

Let’s think an if statement and inside this the appropriate check.

A working code is the following:

Objective-C

The class property [NSDecimalNumber notANumber] is just for this purpose. In some languages NaN != NaN

 

if NSNumber is a NaN, convert it to a double and use the C function isnan():

NSNumber *validNumber = [NSNumber numberWithDouble: 1.];
NSLog( @"%d", isnan(validNumber.doubleValue) ); // prints "0"

NSNumber *nanNumber = [NSNumber numberWithDouble: 0./0.];
NSLog( @"%d", isnan(nanNumber.doubleValue) ); // prints "1"

 

[[NSDecimalNumber notANumber] isEqualToNumber:myNumber]
if ([[NSDecimalNumber decimalNumberWithString:self.price...] isEqual:[NSDecimalNumber notANumber]]) {

//Code

}

SWIFT 

let x = 0.0
let y = x * .infinity
// y is a NaN

// Comparing with the equal-to operator never returns 'true'
print(x == Double.nan)
// Prints "false"
print(y == Double.nan)
// Prints "false"

// Test with the 'isNaN' property instead
print(x.isNaN)
// Prints "false"
print(y.isNaN)
// Prints "true"

tips & tricks

Join 7,719 other subscribers

interview questions


Algorithm Android Android Studio API APP Programming Apps blogging Browser CheatSheets Code Config CSS DATABASE dsa error Features HTML HTML5 IDE installation Interview Questions IOS iPhone javascript Mac objective-c OneDrive OS Placeholder Programming quicktips SDK SEO Settings SMO SQL swift swiftUI Teams Tips & Tricks Tools UI Web Wordpress Xcode


Archives

Discover more from CODE t!ps

Subscribe now to keep reading and get access to the full archive.

Continue reading