Java Number Round roundToNumDigits(double d, int n)

Here you can find the source of roundToNumDigits(double d, int n)

Description

Rounds the input double to n significant digits.

License

Open Source License

Parameter

Parameter Description
d The number to round
n The number of digits to round to

Return

d rounded to n digits

Declaration

public static double roundToNumDigits(double d, int n) 

Method Source Code

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

public class Main {
    /**/*from  ww w  .jav a2  s  . c o m*/
     * Rounds the input double to n significant digits. This code started from
     * an example on
     * http://stackoverflow.com/questions/202302/rounding-to-an-arbitrary-number-of-significant-digits
     *
     * @param d The number to round
     * @param n The number of digits to round to
     * @return d rounded to n digits
     */
    public static double roundToNumDigits(double d, int n) {
        if (d == 0) {
            return 0;
        }

        final long numDs = mostSignificantDigitPosition(d);
        final long power = n - ((numDs > 0) ? numDs : (numDs + 1));

        final double mag = Math.pow(10, power);
        final long shifted = Math.round(d * mag);

        return shifted / mag;
    }

    /**
     * Returns the position of the most significant digit of d.
     *
     * @param d The number to test for position of most significant digit
     * @return the position of the most significant digit
     */
    public static long mostSignificantDigitPosition(double d) {
        double nDigits = Math.log10(Math.abs(d));
        if ((nDigits == (int) nDigits) && (nDigits >= 0)) {
            nDigits += 1;
        }
        return (d == 0) ? 0 : (nDigits > 0) ? (long) Math.ceil(nDigits) : (long) Math.floor(nDigits);
    }
}

Related

  1. roundToNearestN(float value, float n)
  2. roundToNearestPowerOfTen(double value)
  3. roundToNext(int val, int factor)
  4. roundToNextPowerOfTwo(int value)
  5. roundToNthDecimal(double number, int decimals)
  6. roundToPowerOf(int i, int powerOf)
  7. roundToPowerOf10(double value, int powerOf10)
  8. roundToPowerOf2(int value)
  9. roundToPrecision(double number, int precision)