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.

Michael Rivers
  • 920
  • 2
  • 10
  • 17
  • 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`. – jbg Sep 07 '14 at 02:52

2 Answers2

85

You can do:

NSDecimalNumber *decNum = [NSDecimalNumber decimalNumberWithDecimal:[aNumber decimalValue]];
rmaddy
  • 314,917
  • 42
  • 532
  • 579
  • 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. – Michael Rivers Feb 05 '14 at 06:21
  • 1
    `2e+34` is 2 with 34 zeros. Those are the same number expressed in two different ways. – rmaddy Feb 05 '14 at 06:33
21

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)
Eike
  • 2,311
  • 20
  • 31