rickytan
rickytan

Reputation: 110

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

For example:

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

but:

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

Well, here is the code. I'm write a unit test of my code:

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

Upvotes: 0

Views: 125

Answers (1)

Ken Thomases
Ken Thomases

Reputation: 90551

From the 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

Also, further down, Table 4 – NSNumber from Floating Point Value Conversions shows specifically that querying the unsignedIntegerValue of an NSNumber created from a negative floating-point value produces "invalid, erroneous result".

What you're trying to do is inherently undefined and can't be made reliable.

Upvotes: 4

Related Questions