-[NSDecimalNumber longValue] and friends sometimes return (very) incorrect result

Number:rdar://25465729 Date Originated:3/30/2016
Status:Open Resolved:
Product:iOS Product Version:9.3
Classification:Bug Reproducible:Always
Submitted to StackOverflow here: http://stackoverflow.com/questions/36322336/positive-nsdecimalnumber-returns-2s-complement-of-expected-integervalue?noredirect=1#comment60288025_36322336

I've stumbled onto an odd NSDecimalNumber behavior: for some values, invocations of `integerValue`, `longValue`, `longLongValue`, etc., return the an unexpected value. Example:

    let v = NSDecimalNumber(string: "9.821426272392280061")
    v                  // evaluates to 9.821426272392278
    v.intValue         // evaluates to 9
    v.integerValue     // evaluates to -8
    v.longValue        // evaluates to -8
    v.longLongValue    // evaluates to -8

    let v2 = NSDecimalNumber(string: "9.821426272392280060")
    v2                  // evaluates to 9.821426272392278
    v2.intValue         // evaluates to 9
    v2.integerValue     // evaluates to 9
    v2.longValue        // evaluates to 9
    v2.longLongValue    // evaluates to 9

This is using XCode 7.3; I haven't tested using earlier versions of the frameworks.

I've seen a bunch of discussion about unexpected rounding behavior with `NSDecimalNumber`, as well as admonishments not to initialize it with the inherited `NSNumber` initializers, but I haven't seen anything about this specific behavior. Nevertheless there *are* some rather detailed discussions about internal representations and rounding which may contain the nugget I seek, so apologies in advance if I missed it.

This happens in Objc as well.

Steps to Reproduce:
See Description

Expected Results:
NSDecimalNumber *Value methods return consistent results for all values in range.

Actual Results:
For some NSDecimalNumbers with very high precision, values are quite a ways off, and signed flipped.

XCode 7.3, iOS 9.3, Swift 2.2


Simulator, Swift Playgrounds



Status update

This has been marked as a dup of #19812966 by Apple.

Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!