tags:

views:

117

answers:

5

If I have a float value that the user sets, like 1.82, how can I find the next highest .05 value (1.85)?

Is there a simple way or does this take a lot of math? I'm trying to use floor and ceiling to come up with the distance from the float to the next highest and lowest integers, but keep getting stuck, because I'm not sure what to do once I have that info.

Thanks for your consideration!

+10  A: 

Multiply by 20, use ceiling, divide by 20.

Justin
A: 

A great useful and informative resource for Rounding methods.

JadziaMD
A: 

Code for @Justin's answer. Note that this is very easy to generalize.

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

int main(void) {
    int i;
    double numbers[] = {
        1.82, 0.3, 0.2, 0.5, 10000000000.849,
    };

    for (i = 0; i < sizeof(numbers)/sizeof(numbers[0]); ++i) {
        double scaled = ceil(20 * numbers[i]);
        printf("%.2f\n", scaled/20.0);
    }

    return 0;
}
Sinan Ünür
A: 
float fixedCeil(float num, float factor)
{
  float steps = 1.0f / factor;
  return ceil(steps*num)/steps;
}

assert(fixedCeil(2.43f, 0.05f) == 2.45f);

(assert is just fictional)

Jack
A: 

You can use something like

    // Rounds X to the nearest Y
    double round(double x, double y)
    {
        return floor(x / y + 0.5) * y;
    }
Kangkan