Java Double Number Round round(double value, int power)

Here you can find the source of round(double value, int power)

Description

Relaxes precision up to the given power of 2.

License

Apache License

Parameter

Parameter Description
value The value to round.
power Powers of 2 yielding the cutoff value.

Return

The rounded value.

Declaration

public static double round(double value, int power) 

Method Source Code

//package com.java2s;
/*/*  w  w  w  .j  av  a 2 s .c om*/
 * Entwined STM
 * 
 * (c) Copyright 2013 CERN. This software is distributed under the terms of the Apache License Version 2.0, copied
 * verbatim in the file "COPYING". In applying this licence, CERN does not waive the privileges and immunities granted
 * to it by virtue of its status as an Intergovernmental Organization or submit itself to any jurisdiction.
 */

public class Main {
    /**
     * Relaxes precision up to the given power of 2.
     * <p>
     * <b>Note:</b> After applying this method you might still have digits on positions further then requested! This
     * method doesn't guarantee zeroes there, but it makes sure that if there is any difference in the original numbers
     * that is less than <i>pow(2,power)</i> it will be discarded.
     * 
     * @param value The value to round.
     * @param power Powers of 2 yielding the cutoff value.
     * @return The rounded value.
     */
    public static double round(double value, int power) {
        // Divide value by 2^power
        double scaled = Math.scalb(value, -power);
        // Discard the fractional part, multiply back by 2^power
        return Math.scalb(Math.rint(scaled), power);
    }
}

Related

  1. round(double value, int nbDigits)
  2. round(double value, int numberOfDecimalPlaces)
  3. round(double value, int numDecimals)
  4. round(double value, int places)
  5. round(double value, int places)
  6. round(double value, int precision)
  7. round(double value, int precision)
  8. round(double value, int precision)
  9. round(double value, int roundingFactor)