为什么 NSNumber 在转换为无符号整数时舍入负数?

Why does NSNumber round minus number while cast to unsigned integer?

例如:

[@(-2.50001) unsignedIntegerValue] == -3
[@(-2.49999) unsignedIntegerValue] == -2

但是:

[@(-2.50001) integerValue] == -2
[@(-2.49999) integerValue] == -2

好的,这是代码。我正在编写我的代码的单元测试:

- (void)testUnsignedIntegerValue {
    XCTAssertEqual([@(-2.50001) unsignedIntegerValue], (NSUInteger)-3);
    XCTAssertEqual([@(-2.49999) unsignedIntegerValue], (NSUInteger)-2);
}

来自NSNumber docs

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

此外,进一步向下,Table 4 – NSNumber from Floating Point Value Conversions 具体显示查询从负浮点值创建的 NSNumberunsignedIntegerValue 会产生“ 无效,错误结果".

您尝试做的事情本质上是未定义的,无法做到可靠。