Peter Peter - 20 days ago 9
C Question

How to round (up) a decimal to the nearest eighth in C

So I'm wondering how to round a double to the nearest eighth in C (not C++, C#, or Java. I've tried searching the answer before posting here, and that's the only languages I found such a tutorial for.) Does anyone have an idea on how to do this?

An example output is as such: If the inputted number is 0.126, it rounds it up to 0.250. If it's 0.124, it rounds up to 0.125.

Answer

As you stated, you want your number rounded up to the nearest 1/8th.

#include <math.h>
#include <stdio.h>

double roundToEight(double value)
{
    return ceil(value*8)/8;
}

int main()
{
    printf("%f\n",roundEight(12.42)); //12.500
    printf("%f\n",roundEight(12.51)); //12.625
    printf("%f\n",roundEight(12.50)); //12.500
    printf("%f\n",roundEight(-0.24)); //-0.125
    printf("%f\n",roundEight(0.3668)); //0.375

    return 0;
}

If you want negative numbers to be rounded down instead, you can put an if statement there and use floor() instead of ceil() on the negative branch.

Comments