Convert float to int in Objective-C

后端 未结 4 515
半阙折子戏
半阙折子戏 2021-02-02 02:18

How can I convert a float to int while rounding up to the next integer? For example, 1.00001 would go to 2 and 1.9999 would go to 2.

4条回答
  •  [愿得一人]
    2021-02-02 02:48

    float myFloat = 3.333
    
    // for nearest integer rounded up (3.333 -> 4):
    int result = (int)ceilf(myFloat );
    
    // for nearest integer (3.4999 -> 3, 3.5 -> 4):
    int result = (int)roundf(myFloat );
    
    // for nearest integer rounded down (3.999 -> 3):
    int result = (int)floor(myFloat);
    
    // For just an integer value (for which you don't care about accuracy) 
    int result = (int)myFloat;
    

提交回复
热议问题