1

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).

0

5 Answers 5

6

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
2
  • It's incorrect. For example, if you have float a = 1.2f and use loop to sum up a for 100 times, you'll get a float 119.99. Then you cast it in that way, and you'll get 119, not 120
    – Eric
    Nov 18, 2020 at 10:33
  • @Eric: I think you're missing the point of the question - the OP requires truncation, so 119.99 should give 119.
    – Paul R
    Nov 18, 2020 at 11:54
3

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)

2

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

2
  • 1
    It is just that he does not want 4 as the output. He seeks for 3. Jun 12, 2013 at 9:09
  • Looks better. Do the same for -3.9 in case he has to consider negative values too and he's got a good choice. Jun 12, 2013 at 9:34
1

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

0
0

You can simple typecast to int

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.