Java Double Number Round roundDecimal(double x, int d)

Here you can find the source of roundDecimal(double x, int d)

Description

Rounds the number off to a given number of significant digits.

License

Open Source License

Parameter

Parameter Description
x The number to be rounded
d The number of significant digits

Return

x rounded to d significant digits.

Declaration

public static double roundDecimal(double x, int d) 

Method Source Code

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

public class Main {
    /**//from w  w  w  . java 2s.  c  o m
     * Rounds the number off to a given number of
     * significant digits.
     * 
     * @param x The number to be rounded
     * @param d The number of significant digits
     * @return x rounded to d significant digits.
     */
    public static double roundDecimal(double x, int d) {

        if ((d > 0) && (x != 0)) {
            double factor = Math.pow(10, Math.floor(log10(Math.abs(x))) - d + 1);
            x = Math.rint(x / factor) * factor;
        }
        return x;
    }

    /**
     * Returns the logarithm to the base 10
     * 
     * @param x the x-value to be used for the logarithme
     * @return the log to the base 10 of x
     */
    public static double log10(double x) {
        return Math.log(x) * .43429448190325182765112891891660508229439700580366;
    }
}

Related

  1. roundAway(double d)
  2. roundAwayFromZero(double num)
  3. roundBig(double d)
  4. roundDec(float num, int dec)
  5. roundDecimal(Double value)
  6. roundDecimals(double d, int decimalPlaces)
  7. roundDecimals(double x, int decimals)
  8. roundDiv(double a, double b)
  9. roundDouble(double d)