Search code examples
cfunctionroundingfloor

Rounding down a floating point number to an integer value without a floor function in C


I need to write a function in C that rounds down a floating point number to an integer. For example, 10.6 becomes 10. 22.1249 becomes 22. However, I can't use a floor function. Can this be done?


Solution

  • Floor

    Use integer cast to round down float number.

    float yourFloat = 10.5;
    int down = (int)yourfloat; //down = 10.
    

    Nearest integer

    To round to the nearest integer, add 0.5f to your float, then cast.

    float f1 = 10.3, f2 = 10.8;
    int i1, i2;
    i1 = (int)(f1 + 0.5f); //i1 = 10
    i2 = (int)(f2 + 0.5f); //i2 = 11
    

    Ceil

    To round number up, use if statement with some casts:

    int result = (int)yourFloat;
    if (yourFloat - (int)yourFloat > 0) {
        result++;
    }