Java Number Round roundToSignificantDigits(double value, int n)

Here you can find the source of roundToSignificantDigits(double value, int n)

Description

Rounds a number to a given number of significant decimal digits.

License

Open Source License

Parameter

Parameter Description
value the value to round off.
n the number of significant decimal digits desired.

Return

a rounded off number.

Declaration

public static double roundToSignificantDigits(double value, int n) 

Method Source Code

//package com.java2s;

public class Main {
    private static final double TOLERANCE = 0.01;

    /**//w  w  w .j  a v a 2s. c  o m
     * Rounds a number to a given number of significant decimal digits.
     * Note that the number will be left with *only* this number of
     * significant digits regardless of magnitude, e.g. 12345 to 3 digits
     * will be 12300, whereas 0.12345 will be 0.123.
     * 
     * @param value the value to round off.
     * @param n the number of significant decimal digits desired.
     * @return a rounded off number.
     */
    public static double roundToSignificantDigits(double value, int n) {
        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;
    }

    /**
     * Tests whether the two decimal numbers are equal with a tolerance of 0.01.
     * If one or both of the numbers are null, false is returned.
     * 
     * @param d1 the first value.
     * @param d2 the second value.
     * @return true if the two decimal numbers are equal with a tolerance of 0.01.
     */
    public static boolean isEqual(Double d1, Double d2) {
        if (d1 == null || d2 == null) {
            return false;
        }

        return Math.abs(d1 - d2) < TOLERANCE;
    }

    /**
     * Tests whether the two decimal numbers are equal with a tolerance of 0.01.
     * 
     * @param d1 the first value.
     * @param d2 the second value.
     * @return true if the two decimal numbers are equal with a tolerance of 0.01.
     */
    public static boolean isEqual(double d1, double d2) {
        return Math.abs(d1 - d2) < TOLERANCE;
    }
}

Related

  1. roundToPrecision(double number, int precision)
  2. roundToPrecision(float value, int numDecimalPlaces)
  3. roundToQuarterMs(float f)
  4. roundToShort(final double d)
  5. roundToSignificantDigits(double num, int n)
  6. roundToSignificantDigits(double x, double y, int nSignif)
  7. roundToSignificantFigures(double num, int n)
  8. RoundToStr(double value, int dec)
  9. roundToString(double nb2round, int nbOfDigits)