Objective-C Float Rounding

前端 未结 7 1524
执念已碎
执念已碎 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: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)
    

提交回复
热议问题