Peter Peter - 1 year ago 70
C Question

How to round 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?

Thanks in advance,

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download