Convert NSNumber to NSDecimalNumber
Asked Answered
C

2

43

I realize that NSDecimalNumber inherits from NSNumber.

However, I am struggling to figure out how I can init an NSDecimalNumber from an NSNumber or how to convert an NSNumber to an NSDecimalNumber.

I have tried

NSDecimalNumber* d = [aNumber copy];

where aNumber is an NSNumber object to no avail.

Am I missing something?

Thanks.

Choctaw answered 5/2, 2014 at 5:50 Comment(1)
As an aside, [NSNumber copy] is never going to return a NSDecimalNumber… I’m only aware of conversions via NSDecimal (like in the answers below) or via NSString.Phthalein
C
85

You can do:

NSDecimalNumber *decNum = [NSDecimalNumber decimalNumberWithDecimal:[aNumber decimalValue]];
Christy answered 5/2, 2014 at 5:57 Comment(2)
Only problem is that passing an NSNumber with value of 2e+34 ends up with decNum of 2 and 34 zeros. would like it to maintain the same mantissa and exponent.Choctaw
2e+34 is 2 with 34 zeros. Those are the same number expressed in two different ways.Christy
W
22

So:

NSNumber * number = [NSNumber numberWithInt:10];
NSDecimalNumber *d = [NSDecimalNumber decimalNumberWithDecimal:[number decimalValue]];

And in Swift

let number = NSNumber(int: 10)
let dec = NSDecimalNumber(decimal: number.decimalValue)
Wherefrom answered 5/2, 2014 at 5:53 Comment(3)
The 2nd one isn't valid (and in both cases d needs to be a pointer).Christy
@Christy what are you talking about?Baptiste
@Andy The answer has been edited twice (as of this comment) since my original comment. Look at the edit history to see what the answer looked like at the time of my comment.Christy

© 2022 - 2024 — McMap. All rights reserved.