Java Number Round roundToSignificantDigits(double x, double y, int nSignif)

Here you can find the source of roundToSignificantDigits(double x, double y, int nSignif)

Description

Function to round x and y to a number of digits enough to show the difference in range This is for pretty printing only.

License

Open Source License

Declaration

public static Double[] roundToSignificantDigits(double x, double y, int nSignif) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /** Function to round x and y to a number of digits enough to show the difference in range
     * This is for pretty printing only.
     * */// w w  w .j a v  a2s.c  o m
    public static Double[] roundToSignificantDigits(double x, double y, int nSignif) {

        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) {
            // Round to 2 digits regardless of how large is the diff
            rounded[0] = Math.rint(x * Math.pow(10.0, nSignif)) / Math.pow(10.0, nSignif);
            rounded[1] = Math.rint(y * Math.pow(10.0, nSignif)) / Math.pow(10.0, nSignif);
            return rounded;
        } else {
            // Diff is small, < 1. See how many digits you need to approximate
            // Get number of leading zeros
            int nzeros = (int) (Math.ceil(Math.abs(Math.log10(diff))) + nSignif);
            rounded[0] = Math.rint(x * Math.pow(10.0, nzeros)) / Math.pow(10.0, nzeros);
            rounded[1] = Math.rint(y * Math.pow(10.0, nzeros)) / Math.pow(10.0, nzeros);
            return rounded;
        }
    }
}

Related

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