Peter
Peter

Reputation: 11

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.

Upvotes: 0

Views: 2214

Answers (2)

tddguru
tddguru

Reputation: 392

Here is a function that will handle rounding:

double roundToNearestEighths(double value) {
    if (value >= 0)
       return floor(value * 8.0 + 0.5) / 8.0;
    else
       return -floor(-value * 8.0 + 0.5) / 8.0;
}

Upvotes: 1

MrLumie
MrLumie

Reputation: 247

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.

Upvotes: 2

Related Questions