Java Number Round roundToNDecimalPlaces(final double in, final int n)

Here you can find the source of roundToNDecimalPlaces(final double in, final int n)

Description

Rounds the double to the given number of decimal places.

License

Open Source License

Declaration

public static double roundToNDecimalPlaces(final double in, final int n) 

Method Source Code

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

public class Main {
    /**/*w w w .j a v  a 2s  .  co m*/
     * Rounds the double to the given number of decimal places.
     * For example, rounding 3.1415926 to 3 places would give 3.142.
     * The requirement is that it works exactly as writing a number down with string.format and reading back in.
     */
    public static double roundToNDecimalPlaces(final double in, final int n) {
        if (n < 1) {
            throw new IllegalArgumentException("cannot round to " + n + " decimal places");
        }

        final double mult = Math.pow(10, n);
        return Math.round((in + Math.ulp(in)) * mult) / mult;
    }
}

Related

  1. roundToMil(double val)
  2. roundToMultiple(int value, int divisor)
  3. roundToMultiple(int value, int multipleOf)
  4. roundToMultipleXLength(int inLength, int multipler)
  5. roundToN(double d, int n)
  6. roundToNDigits(double d, int n)
  7. roundToNearest(double d)
  8. roundToNearest(double number)
  9. roundToNearest(int num, int nearest)