Jules
Jules

Reputation: 7766

Objective-C, how do I convert a double to an int?

I must be doing something really obviously wrong, but I can't see it.

alt text

Upvotes: 38

Views: 54046

Answers (5)

Khushal iOS
Khushal iOS

Reputation: 311

try this

NSInteger number=33;
NSUInteger count = (NSInteger)[number];

here, NSUInteger is long. number is NSInteger

Upvotes: 1

user4951
user4951

Reputation: 33080

double myDouble = 3.2;

int myInt = @(myDouble).intValue;

Sample of code I actually use:

NSNumber * percentLike1 = @(@(self.percentLike.doubleValue*100).integerValue);

Upvotes: -5

AechoLiu
AechoLiu

Reputation: 18378

intValue is a method for a NSNumber instance. For scale type like int, double, and float, they are not class type. So, they have no methods. Some languages like C# may wrap int, or double as a object, and they can be transfered to each other by a sub-routine.

Upvotes: 1

Vladimir
Vladimir

Reputation: 647

Just converting mentioned above is good enough though you might want to use floor() or ceil() functions before that.

Upvotes: 4

Georg Schölly
Georg Schölly

Reputation: 126105

A double is a C type, not an Objective-C object. Hence you use C casts:

double myDouble = 3.2;
int myInt = (int)myDouble;

Upvotes: 93

Related Questions