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!
double roundUp(double x, double f) {
return f * Math.ceil(x / f);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With