2

I have an situation where I get an NSDecimal, and I need an NSInteger. I do know it is a very small value (this is absolutely sure). It won't be bigger than 100. So It would be perfectly fine to cast it to NSInteger, no overflow would happen.

How could this be done? There's just an -doubleValue method in NSDecimal.

dontWatchMyProfile
  • 45,440
  • 50
  • 177
  • 260
  • Are you starting with an `NSDecimal` or an `NSDecimalNumber`? `NSDecimalNumber` has a `-doubleValue` method, but `NSDecimal` doesn't. – kubi Mar 30 '10 at 20:58

3 Answers3

13

First convert it to an NSDecimalNumber. NSDecimalNumber is a subclass of NSNumber so you can use all of the NSNumber methods:

NSDecimalNumber *myNSDecimalNumber = [NSDecimalNumber decimalNumberWithDecimal:myNSDecimal];
NSInteger myInt = [myNSDecimalNumber intValue];
pheelicks
  • 7,461
  • 2
  • 45
  • 50
4

Look at the NSDecimalNumber Class Reference. Create an NSDecimalNumber from your NSDecimal, then call intValue.

NSDecimalNumber * decNum  = [NSDecimalNumber decimalNumberWithDecimal:yourDecimal];

int yourInt = [decNum intValue];
Chris Frederick
  • 5,482
  • 3
  • 36
  • 44
cagreen
  • 1,627
  • 1
  • 14
  • 29
1

you could always grab the doubleValue (I am assuming you have an NSDecimalNumber) and typecast that to int.

Steven Noyes
  • 1,549
  • 1
  • 11
  • 16