Matan
Matan

Reputation: 456

Converting float to int without rounding

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

Answers (5)

Nitin Gohel
Nitin Gohel

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

Hermann Klecker
Hermann Klecker

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

Jabson
Jabson

Reputation: 1703

You can simple typecast to int

Upvotes: 0

Matt Rees
Matt Rees

Reputation: 884

Just cast the float to an int and it will truncate your result.

Upvotes: 1

Paul R
Paul R

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

Related Questions