开发者

How to convert a double to NSInteger?

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


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;
}


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.


but anyway, assuming you want no rounding, i believe this should work simply

double myDouble = 10.4223;
NSInteger myInt = myDouble;

edit for rounding: (i'm sure theres a much simpler (and precise) way to do this.. (this also doesn't account for negative numbers or maximum boundaries)

double myDecimal = myDouble - myInt;
if(myDecimal < 0.50)
{
//do nothing
}
else
{
myInt = myInt + 1;
}


NSInteger is a typedef, it's the same as using an int. Just assign the value like:

double d;
NSInteger i = d;


JesseNaugher mentions rounding and I note the OP needs were met with a simple truncate, but in the spirit of full generalisation it's worth remembering the simple trick of adding 0.5 to the double before invoking floor() to achieve rounding. Extending Jonathan Grynspan's comment: NSInteger myInt = floor(myDouble + 0.5); i.e., rounding up in absolute terms. If rounding 'up' means rounding away from zero a more convoluted approach is needed: NSInteger myInt = floor( myDouble + (myDouble < 0.0 ? -0.5 : 0.5) );

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜