Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you round up to nearest multiple of a given factor with floating point numbers?

The question is how to round a given value to the nearest "almost exact" multiple of a given factor, f. For example:

If f = 2.6, then every "roundUp(x, 2.6)" invocation would return a number from the set {0, +/- 2.6, +/- 2*2.6, +/- 3*2.6, ...}

Typically, my f is either a power of 10 (where the power is positive or negative) or 1/2 said power of 10.

Another example: f = 0.001 , should round up to the nearest integer multiple of 0.001, e.g., {0, +/- 0.001, +/- 2*0.001, +/- 3*0.001}.

UPDATE: I want the result of roundUp(x, f) to be the "ceiling" of the result, that is, the smallest element from the set of multiples greater than or equal to x (if that's the proper way to word it). See my answer below for a not-so-elegant solution (that appears to work for all the cases I can through at it).

All I need is a decent floating point approximation (using double in Java). Any advice greatly appreciated!

like image 846
les2 Avatar asked Mar 27 '12 13:03

les2


1 Answers

double roundUp(double x, double f) {
  return f * Math.ceil(x / f);
}
like image 56
x539 Avatar answered Nov 05 '22 06:11

x539