Java Double Number Round round(double v, int precision)

Here you can find the source of round(double v, int precision)

Description

Fast way of truncating a double to a certain number of digits.

License

Open Source License

Parameter

Parameter Description
v a parameter
precision a parameter

Declaration

public static double round(double v, int precision) 

Method Source Code

//package com.java2s;
/* //from w ww . ja v a2 s. co m
 * This file is part of Transitime.org
 * 
 * Transitime.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License (GPL) as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * Transitime.org 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 Transitime.org .  If not, see <http://www.gnu.org/licenses/>.
 */

public class Main {
    private static long TENS[] = new long[19];

    /**
     * Fast way of truncating a double to a certain number of digits.
     * Certainly useful for latitudes and longitudes.
     * 
     * @param v
     * @param precision
     * @return
     */
    public static double round(double v, int precision) {
        assert precision >= 0 && precision < TENS.length;
        double unscaled = v * TENS[precision];
        if (unscaled < Long.MIN_VALUE || unscaled > Long.MAX_VALUE)
            return v;
        long unscaledLong = (long) (unscaled + (v < 0 ? -0.5 : 0.5));
        return (double) unscaledLong / TENS[precision];
    }
}

Related

  1. round(double round, int decimal, int ceilOrFloor)
  2. round(double Rpred[][])
  3. Round(double Rval, int Rpl)
  4. round(double toRound)
  5. round(double v)
  6. round(double val)
  7. round(double val)
  8. round(double val)
  9. round(double val, int decimalHouses)