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

introundToPowerOf2(int value)
round To Power Of
value--;
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
return value + 1;
doubleroundToPrecision(double number, int precision)
round To Precision
double decimalPlaces = Math.pow(10, precision);
return Math.round(decimalPlaces * number) / decimalPlaces;
floatroundToPrecision(float value, int numDecimalPlaces)
Rounds a number to a (generally) smaller number of decmiel places.
float multiplyFactor = (float) Math.pow(10f, numDecimalPlaces);
float valueMultiplied = value * multiplyFactor;
return (float) Math.round(valueMultiplied) / multiplyFactor;
floatroundToQuarterMs(float f)
rounds to nearest increment of 0.25
return ((float) Math.round(f * 4)) / 4;
shortroundToShort(final double d)
round To Short
return (short) (d + 0.5);
doubleroundToSignificantDigits(double num, int n)
round To Significant Digits
if (num == 0) {
    return 0;
} else if (n == 0) {
    return Math.round(num);
String s = num + "";
int index = s.indexOf(".");
while (n >= s.length() - index) {
...
doubleroundToSignificantDigits(double value, int n)
Rounds a number to a given number of significant decimal digits.
if (isEqual(value, 0.0)) {
    return 0.0;
final double d = Math.ceil(Math.log10(value < 0.0 ? -value : value));
final int power = n - (int) d;
final double magnitude = Math.pow(10.0, power);
final long shifted = Math.round(value * magnitude);
return shifted / magnitude;
...
Double[]roundToSignificantDigits(double x, double y, int nSignif)
Function to round x and y to a number of digits enough to show the difference in range This is for pretty printing only.
Double[] rounded = new Double[2];
double diff = Math.abs(x - y);
if (diff < 1e-16) {
    rounded[0] = x;
    rounded[1] = y;
    return rounded;
if (diff > 1) {
...
doubleroundToSignificantFigures(double num, int n)
round To Significant Figures
if (num == 0) {
    return 0;
final double d = Math.ceil(Math.log10(num < 0 ? -num : num));
final int power = n - (int) d;
final double magnitude = Math.pow(10, power);
final long shifted = Math.round(num * magnitude);
return shifted / magnitude;
...
StringRoundToStr(double value, int dec)
Round To Str
return String.format("%8." + dec + "%", value);