Convert float to int in Objective-C

后端 未结 4 523
半阙折子戏
半阙折子戏 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:38

    You can use following C methods to get the int values from different dataTypes.

    extern float ceilf(float);
    extern double ceil(double);
    extern long double ceill(long double);
    

    These functions return float, double and long double respectively. But the job of these function is to get ceil of or floor of the argument. As in http://en.wikipedia.org/wiki/Floor_and_ceiling_functions

    Then you can cast the return value to desired type like.

    int intVariable = (int)ceilf(floatValueToConvert);
    

    Hope it is helpful.

提交回复
热议问题