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?
Asked
Active
Viewed 348 times
5

phi
- 10,634
- 6
- 53
- 88
-
7There is no integer value which represents NaN. – Martin R Jan 07 '19 at 12:25
-
@MartinR has this `9` something to do with maximal value for `Int64` (9223372036854775807)? – Robert Dresler Jan 07 '19 at 12:26
-
@RobertDresler Definitely not. I would guess this will have something to do with the binary value of `NaN` representation. – Sulthan Jan 07 '19 at 12:30
-
4According to Apple doc "If you ask an NSNumber object for its value using a type that cannot hold the value, you get back an erroneous result", could this be it? – Joakim Danielson Jan 07 '19 at 12:31
-
@JoakimDanielson it would make sense, for `Int32` it is `-2147483648`. But still, why not `-9223372036854775808` for `Int64` instead of `9`? – Robert Dresler Jan 07 '19 at 12:32
-
Thanks everyone, I learned a lot here! – phi Jan 07 '19 at 13:08
1 Answers
6
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

Damiaan Dufaux
- 4,427
- 1
- 22
- 33