Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a double to NSInteger?

Very simple question here. I have a double that I wish to convert back to a NSInteger, truncating to the units place. How would I do that?

like image 549
sudo rm -rf Avatar asked Jan 12 '11 16:01

sudo rm -rf


2 Answers

Truncation is an implicit conversion:

NSInteger theInteger = theDouble;

That's assuming you're not checking the value is within NSInteger's range. If you want to do that, you'll have to add some branching:

NSInteger theInteger = 0;
if (theDouble > NSIntegerMax) {
    // ...
} else if (theDouble < NSIntegerMin) {
    // ...
} else {
    theInteger = theDouble;
}
like image 76
Jonathan Grynspan Avatar answered Sep 22 '22 10:09

Jonathan Grynspan


NSInteger is a typedef for a C type. So you can just do:

double originalNumber;
NSInteger integerNumber = (NSInteger)originalNumber;

Which, per the C spec, will truncate originalNumber.

like image 22
Tommy Avatar answered Sep 25 '22 10:09

Tommy