Java BigDecimal Round round(BigDecimal d, int decimalDigits, RoundingMode rmode)

Here you can find the source of round(BigDecimal d, int decimalDigits, RoundingMode rmode)

Description

Round the passed BigDecimal so that only decimalDigits remain after the point.

License

Open Source License

Parameter

Parameter Description
d the decimal to use, eg "123.4567".
decimalDigits the number of digits after the point, eg 1.
rmode how to round.

Return

d rounded so that only decimalDigits remain, eg "123.5".

Declaration

static public BigDecimal round(BigDecimal d, int decimalDigits, RoundingMode rmode) 

Method Source Code


//package com.java2s;
/*//from w  ww .j ava  2s. c o m
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 * 
 * Copyright 2011 OpenConcerto, by ILM Informatique. All rights reserved.
 * 
 * The contents of this file are subject to the terms of the GNU General Public License Version 3
 * only ("GPL"). You may not use this file except in compliance with the License. You can obtain a
 * copy of the License at http://www.gnu.org/licenses/gpl-3.0.html See the License for the specific
 * language governing permissions and limitations under the License.
 * 
 * When distributing the software, include this License Header Notice in each file.
 */

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

public class Main {
    static public BigDecimal round(BigDecimal d, int decimalDigits) {
        return round(d, decimalDigits, RoundingMode.HALF_UP);
    }

    /**
     * Round the passed BigDecimal so that only <code>decimalDigits</code> remain after the point.
     * 
     * @param d the decimal to use, eg "123.4567".
     * @param decimalDigits the number of digits after the point, eg 1.
     * @param rmode how to round.
     * @return d rounded so that only <code>decimalDigits</code> remain, eg "123.5".
     */
    static public BigDecimal round(BigDecimal d, int decimalDigits, RoundingMode rmode) {
        return d.round(new MathContext(intDigits(d) + decimalDigits, rmode));
    }

    /**
     * The number of int digits.
     * 
     * @param d the decimal to use, eg "123.45".
     * @return number of int digits, never less than 1, eg 3.
     */
    static public int intDigits(BigDecimal d) {
        return Math.max(1, d.precision() - d.scale());
    }
}

Related

  1. getStringValue(BigDecimal val, int newScale, int roundingMode)
  2. magicRound(BigDecimal value)
  3. round(BigDecimal amount)
  4. round(BigDecimal aValue, int aScale)
  5. round(BigDecimal b, int precision)
  6. round(BigDecimal d, int decimalPlace)
  7. round(BigDecimal decimal)
  8. round(BigDecimal decimal)
  9. round(BigDecimal decimal, int decimalDigits)