How do you round to the nearest multiple of a given multiplier 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 instance:

If f = 2.6, then each call to roundUp (x, 2.6) will 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 of that power of 10.

Another example: f = 0.001, should round to the nearest integer multiple of 0.001, for example, {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, i.e. the smallest element of the set of multiple values โ€‹โ€‹greater than or equal to x (if this is the correct way the word is). See my answer below for a not-so-elegant solution (which seems to work in all cases through which I can on it).

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

+4
source share
1 answer
double roundUp(double x, double f) { return f * Math.ceil(x / f); } 
+11
source

Source: https://habr.com/ru/post/1403661/


All Articles