Objective-C Float Rounding

前端 未结 7 1486
执念已碎
执念已碎 2020-12-16 09:26

How might I round a float to the nearest integer in Objective-C:

Example:

float f = 45.698f;
int rounded = _______;
NSLog(@\"the rounded float is %i\         


        
相关标签:
7条回答
  • 2020-12-16 09:38

    Use the C standard function family round(). roundf() for float, round() for double, and roundl() for long double. You can then cast the result to the integer type of your choice.

    0 讨论(0)
  • 2020-12-16 09:40

    For round float to nearest integer use roundf()

    roundf(3.2) // 3
    roundf(3.6) // 4
    

    You can also use ceil() function for always get upper value from float.

    ceil(3.2) // 4
    ceil(3.6) // 4
    

    And for lowest value floor()

    floorf(3.2) //3
    floorf(3.6) //3
    
    0 讨论(0)
  • 2020-12-16 09:42

    The easiest way to round a float in objective-c is lroundf:

    float yourFloat = 3.14;
    int roundedFloat = lroundf(yourFloat); 
    NSLog(@"%d",roundedFloat);
    
    0 讨论(0)
  • 2020-12-16 09:47

    The recommended way is in this answer: https://stackoverflow.com/a/4702539/308315


    Original answer:

    cast it to an int after adding 0.5.

    So

    NSLog (@"the rounded float is %i", (int) (f + 0.5));
    

    Edit: the way you asked for:

    int rounded = (f + 0.5);
    
    
    NSLog (@"the rounded float is %i", rounded);
    
    0 讨论(0)
  • 2020-12-16 09:47

    If in case you want round float value in integer below is the simple method for rounding the float value in objective C.

    int roundedValue = roundf(Your float value);
    
    0 讨论(0)
  • 2020-12-16 09:56

    let's do tried and checkout

    //Your Number to Round (can be predefined or whatever you need it to be)
    float numberToRound = 1.12345;
    float min = ([ [[NSString alloc]initWithFormat:@"%.0f",numberToRound] floatValue]);
    float max = min + 1;
    float maxdif = max - numberToRound;
    if (maxdif > .5) {
        numberToRound = min;
    }else{
        numberToRound = max;
    }
    //numberToRound will now equal it's closest whole number (in this case, it's 1)
    
    0 讨论(0)
提交回复
热议问题