Here you can find the source of round(final double val, final int decimals)
Parameter | Description |
---|---|
val | The value to round. |
decimals | The number of decimals to round to. |
public static double round(final double val, final int decimals)
//package com.java2s; /******************************************************************************* * This file is part of jasima, v1.3, the Java simulator for manufacturing and * logistics.//from w w w .j ava2 s .co m * * Copyright (c) 2015 jasima solutions UG * Copyright (c) 2010-2015 Torsten Hildebrandt and jasima contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ public class Main { /** * Rounds the given double value to a certain number of decimal places. * {@code decimals} can be positive or negative. * * @see #round(double[], int) * @param val * The value to round. * @param decimals * The number of decimals to round to. * @return The rounded values. */ public static double round(final double val, final int decimals) { if (decimals >= 0) { long fact = powerOfTen(decimals); return Math.round(val * fact) / ((double) fact); } else { long fact = powerOfTen(-decimals); return Math.round(val / fact) * ((double) fact); } } /** * Rounds all values in the double array {@code vs} to a certain number of * decimal places. This method does not create a copy of {@code vs}, but * modifies its contents. * * @return the parameter {@code vs} to allow easy chaining of method calls. * * @see #round(double, int) * @param vs * An array of doubles to round. * @param decimals * The number of decimals to round the values. * @return An array with rounded values. */ public static double[] round(final double[] vs, final int decimals) { for (int i = 0; i < vs.length; i++) { vs[i] = round(vs[i], decimals); } return vs; } private static long powerOfTen(int exp) { assert exp >= 0; long fact = 1; for (int i = 0; i < exp; i++) { fact *= 10; } return fact; } }