Reputation: 456
I want to convert a decimal number to an int without rounding it, for example: if the number is 3.9 it will be turned into 3 (if it would have been rounded it would be 4).
Upvotes: 1
Views: 15674
Reputation: 49710
you can do like this bellow :-
float myFloat = 3.9;
int result1 = (int)ceilf(myFloat );
NSLog(@"%d",result1);
int result2 = (int)roundf(myFloat );
NSLog(@"%d",result2);
int result3 = (int)floor(myFloat);
NSLog(@"%d",result3);
int result4 = (int) (myFloat);
NSLog(@"%d",result4);
OUTPUT IS 4 4 3 3
Upvotes: 2
Reputation: 14068
It depends on how you want the negative values be treated. Typecasting to int would just truncate in that way that the part left of the decimal point will remain. -3.9f would turn into -3. Using floor before casting would ensure that it results in -4. (all within the variable type boundaries of course)
Upvotes: 3
Reputation: 212929
You generally don't need to do anything special, as by default a cast from float/double to an integer type results in truncation:
float f = 3.9f;
int i = (int)f; // i = 3
Upvotes: 6