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.
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];
Look at the NSDecimalNumber
Class Reference. Create an NSDecimalNumber
from your NSDecimal
, then call intValue
.
NSDecimalNumber * decNum = [NSDecimalNumber decimalNumberWithDecimal:yourDecimal];
int yourInt = [decNum intValue];
you could always grab the doubleValue (I am assuming you have an NSDecimalNumber) and typecast that to int.
精彩评论