为啥 NSDecimalNumber.notANumber.intValue 返回 9?

Posted

技术标签:

【中文标题】为啥 NSDecimalNumber.notANumber.intValue 返回 9?【英文标题】:Why does NSDecimalNumber.notANumber.intValue return 9?为什么 NSDecimalNumber.notANumber.intValue 返回 9? 【发布时间】:2019-01-07 12:20:18 【问题描述】:

我在我的代码中发现了一个由 NSDecimalNumber.notANumber.intValue 返回 9 引起的错误,而我预计 NaN(如 floatValuedoubleValue 返回)。有人知道为什么吗?

【问题讨论】:

没有代表NaN的整数值。 @MartinR 有这个 9Int64 (9223372036854775807) 的最大值有关吗? @RobertDresler 绝对不是。我猜这与NaN 表示的二进制值有关。 根据 Apple 文档“如果您使用无法保存该值的类型向 NSNumber 对象询问其值,您会得到错误的结果”,可能是这样吗? @JoakimDanielson 这很有意义,对于Int32 它是-2147483648。但是,为什么不用-9223372036854775808 代替Int64 而不是9 【参考方案1】:

就像 Joakim Danielson 提到的并在 Apple Developer Documentation 中提到的那样

...由于数字类型具有不同的存储能力,尝试使用一种类型的值进行初始化并访问另一种类型的值可能会产生错误的结果...

而且由于 Swift 的 Int 结构不能表示 NaN 值,你会得到这个错误的结果。

相反,您可以使用 Int 的 Failable Initialiser init(exactly:) 将您的 NSDecimalNumber 转换为 Int?,该 Int? 将包含它的值,或者如果它不能由 Int 表示,则为 nil

let strangeNumber = NSDecimalNumber.notANumber          // nan
let integerRepresentation = Int(exactly: strangeNumber) // nil

【讨论】:

在 Swift 中你应该使用Decimal.nan,而不是NSDecimalNumber

以上是关于为啥 NSDecimalNumber.notANumber.intValue 返回 9?的主要内容,如果未能解决你的问题,请参考以下文章