开发者

How to cast an NSDecimal value into an NSInteger value?

开发者 https://www.devze.com 2022-12-25 07:46 出处:网络
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

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号