Round to the next 0.05 in C

Consider a float value, such as 1.82 , set by the user. How to find the next highest value .05? For this example, the next highest value is 1.85.

Is there a simple way or complex algorithm required? I tried using the floor and ceiling functions to come up with the distance from the float to the next highest and lowest integer value. But I'm not sure how to act as soon as I have this information.

Thanks.

0
c
source share
5 answers

Multiply by 20, use the ceiling, divide by 20.

+9
source share

Excellent useful and informative resource for rounding methods .

0
source share

Code for @Justin's answer. Please 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; } 
0
source share
 float fixedCeil(float num, float factor) { float steps = 1.0f / factor; return ceil(steps*num)/steps; } assert(fixedCeil(2.43f, 0.05f) == 2.45f); 

(statement is simply fictitious)

0
source share

You can use something like

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

All Articles