Java Number Round roundToN(double d, int n)

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

Description

Rounds the d to n decimal places.

License

Apache License

Parameter

Parameter Description
d - to be rounded
n - decimal places

Return

- the rounded value

Declaration

public static double roundToN(double d, int n) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**//from  ww  w  . j  a  va  2 s. c  om
     * Rounds the d to n decimal places. Uses pow and round methods - do not bother to use in a loop, if required,
     * unfold the pow method.
     * 
     * @param d
     *            - to be rounded
     * @param n
     *            - decimal places
     * @return - the rounded value
     */
    public static double roundToN(double d, int n) {
        // may lose some precision due to fp errors

        double places = StrictMath.pow(10, n);

        double p = StrictMath.round(d * places) / places;

        return p;
    }
}

Related

  1. roundToInterval(float num, float interval)
  2. roundToMil(double val)
  3. roundToMultiple(int value, int divisor)
  4. roundToMultiple(int value, int multipleOf)
  5. roundToMultipleXLength(int inLength, int multipler)
  6. roundToNDecimalPlaces(final double in, final int n)
  7. roundToNDigits(double d, int n)
  8. roundToNearest(double d)
  9. roundToNearest(double number)