Java Utililty Methods Number Round

List of utility methods to do Number Round

Description

The list of methods to do Number Round are organized into topic(s).

Method

longround(final long timeMs, final int precision)
round
final long scale = (long) Math.pow(10, precision);
return ((timeMs) / scale) * scale;
intround(int a, int cutOfDigits)
Math#round(double) -like operation for integers, e.g.:
  • 1234, 3 --> 1000 (like floor, since digits are < 5)
  • 1234, 2 --> 1200 (like floor, since digits are < 5)
  • 1234, 1 --> 1230 (like floor, since digits are < 5)
  • 5678, 3 --> 6000 (like ceil, since digits are >= 5)
  • 5678, 2 --> 5700 (like ceil, since digits are >= 5)
  • 5678, 1 --> 5680 (like ceil, since digits are >= 5)
Some "unusual" cases:
  • 1234, 5 --> 0 (like floor, since digits are < 5)
  • 1234, 4 --> 0 (like floor, since digits are < 5)
  • 1234, 0 --> 1234 (like floor, since digits are < 5)
  • 1234, -1 --> 1234 (like floor, since digits are < 5)
  • 5678, 5 --> 100000 (like ceil, since digits are >= 5)
  • 5678, 4 --> 10000 (like ceil, since digits are >= 5)
  • 5678, 0 --> 5678 (like ceil, since digits are >= 5)
  • 5678, -1 --> 5678 (like ceil, since digits are >= 5)
if (cutOfDigits <= 0)
    return a;
int fac = 1;
while (--cutOfDigits >= 0)
    fac *= 10;
int ret = (a / fac) * fac;
if (a - ret > fac / 2)
    ret += fac;
...
intround(int f)
round
return f < 0 ? -((-f + 32768) & ~0xFFFF) : (f + 32768) & ~0xFFFF;
intround(int n)
round
if (n > 0) {
    if ((n & 0x8000) != 0) {
        return (((n + 0x10000) >> 16) << 16);
    } else {
        return (((n) >> 16) << 16);
} else {
    int k;
...
intround(int start, int boundary)
round
return (start + boundary) & ~boundary;
doubleround(int t, int n, int decimals)
round
double exp = Math.pow(10, decimals);
return Math.round(exp * t / n) / exp;
intround(int top, int div2, int divisor)
Specialized rounding for use with integer wavelet transform.
if (top > 0)
    return (top + div2) / divisor;
else
    return (top - div2) / divisor;
intround(int x, int quantum)
Returns nearest integer to x, divisible by quantum.
int ceil = ceil(x, quantum);
int floor = floor(x, quantum);
return (ceil - x < x - floor) ? ceil : floor;
intround(Integer a)
Round.
return Math.round(a.floatValue());
Numberround(Number number, Number unit)
round
double n = number.doubleValue();
double u = unit.doubleValue();
double r = Math.IEEEremainder(n, u);
if (r < n / 2) {
    n -= r;
} else {
    n = n + u - r;
return new Double(n);