Rounds a double to a specified number of decimal places. - Java java.lang

Java examples for java.lang:double

Description

Rounds a double to a specified number of decimal places.

Demo Code

/*/*  w ww  .ja v  a2 s.  c  om*/
 * Java-Math is a math library written for Java 1.6+ that is primarily 
 * intended to help with 2D and 3D graphics, physics, and other related
 * mathematical operations. 
 *  
 * Copyright (C) 2014  Alec Sobeck and Matthew Robertson
 *
 * Java-Math 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 2 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, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
//package com.java2s;
import java.math.BigDecimal;

public class Main {
    /**
     * Rounds a double to a specified number of decimal places.
     * @param value the double to round to a specified number of decimal places
     * @param places the int representing the number of decimal places in the result
     * @return a double which is the given value rounded to the specified number of decimal places
     */
    public static double round(double value, int places) {
        if (places < 0) {
            throw new IllegalArgumentException();
        }
        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(places, BigDecimal.ROUND_HALF_UP);
        return bd.doubleValue();
    }
}

Related Tutorials