Java Number Round roundValue(Double value)

Here you can find the source of roundValue(Double value)

Description

Rounds to 2 significant figures.

License

Open Source License

Declaration

protected static double roundValue(Double value) 

Method Source Code

//package com.java2s;
/*//  w  w w  .  ja  v  a 2  s  .c  om
 * Boltzmann 3D, a kinetic theory demonstrator
 * Copyright (C) 2013 Dr. Randall B. Shirts
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    /** Rounds to 2 significant figures. */
    protected static double roundValue(Double value) {
        if (value.isInfinite() || value.isNaN() || value == 0)
            return value;

        double val = value;
        int shift = 0;
        if (Math.abs(val) >= 1) // |val| >= 1
        {
            //Make sure we're starting with a value >= 10 (2 digits).
            val *= 10;

            //Consider the two leading numbers.
            while (Math.abs(val) > 100) {
                val /= 10.0;
                shift++;
            }

            //Set all lesser numbers to zero.
            val = Math.round(val);

            //Restore original magnitude.
            for (; shift > 0; shift--)
                val *= 10;

            //One last divide to offset the first multiplication.
            val /= 10;
        } else // 0 < |val| < 1
        {
            //Consider the two leading numbers.
            while (Math.abs(val) < 10) {
                val *= 10;
                shift++;
            }

            //Set all lesser numbers to zero.
            val = Math.round(val);

            //Restore original magnitude.
            for (; shift > 0; shift--)
                val /= 10.0;
        }

        return val;
    }
}

Related

  1. roundUpToPowerOfTwo(int p_151236_0_)
  2. roundUpToPowerOfTwo(int v)
  3. roundUpToPowerOfTwo(int x)
  4. roundUpToTheNextHighestPowerOf2(int v)
  5. roundUpToTwo(Double number)
  6. roundValue(final double value)
  7. roundValues(Double value1, Double value2)
  8. roundValueToUnit(final double graphValue, final double graphUnit, final boolean isMinValue)
  9. roundy(double a)