Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does NSDecimalNumber.notANumber.intValue return 9?

I found a bug in my code that is caused by NSDecimalNumber.notANumber.intValue returning 9, while I would expect NaN (as floatValue or doubleValue return). Does anybody know why?

enter image description here

like image 870
phi Avatar asked Jan 07 '19 12:01

phi


1 Answers

Like mentioned by Joakim Danielson and noted in the Apple Developer Documentation

... Because numeric types have different storage capabilities, attempting to initialize with a value of one type and access the value of another type may produce an erroneous result ...

And since Swift's Int struct cannot represent NaN values, you get this erroneous result.

Instead you could use Int's Failable Initialiser init(exactly:) that converts your NSDecimalNumber to an Int? that will either contain it's value or be nil if it is not representable by an Int.

let strangeNumber = NSDecimalNumber.notANumber          // nan
let integerRepresentation = Int(exactly: strangeNumber) // nil
like image 105
Damiaan Dufaux Avatar answered Oct 11 '22 20:10

Damiaan Dufaux