Java BigDecimal Round roundTo(final BigDecimal bd, final int numberOfDecPlaces, final int finalScale)

Here you can find the source of roundTo(final BigDecimal bd, final int numberOfDecPlaces, final int finalScale)

Description

returns a new BigDecimal with correct scale after being round to n dec places.

License

Apache License

Parameter

Parameter Description
bd value
numberOfDecPlaces number of dec place to round to
finalScale final scale of result (typically numberOfDecPlaces < finalScale);

Return

new bd or null

Declaration

public static BigDecimal roundTo(final BigDecimal bd, final int numberOfDecPlaces, final int finalScale) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.math.BigDecimal;

public class Main {
    /**/* w w w.  j a  v a2  s .co  m*/
     * returns a new BigDecimal with correct scale after being round to n dec places.
     *
     * @param bd value
     * @param numberOfDecPlaces number of dec place to round to
     * @param finalScale final scale of result (typically numberOfDecPlaces < finalScale);
     * @return new bd or null
     */
    public static BigDecimal roundTo(final BigDecimal bd, final int numberOfDecPlaces, final int finalScale) {
        return setScale(setScale(bd, numberOfDecPlaces, BigDecimal.ROUND_HALF_UP), finalScale);
    }

    /**
     * returns a new BigDecimal with correct scale.
     *
     * @param bd
     * @return new bd or null
     */
    public static BigDecimal setScale(final BigDecimal bd, final int scale) {
        return setScale(bd, scale, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * returns a new BigDecimal with correct Scale.
     *
     * @param bd
     * @return new bd or null
     */
    public static BigDecimal setScale(final BigDecimal bd, final Integer scale) {
        return setScale(bd, scale, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * returns a new BigDecimal with correct Scales.PERCENT_SCALE. This is used by the table renderer.
     *
     * @param bd
     * @return new bd or null
     */
    public static BigDecimal setScale(final BigDecimal bd, final Integer scale, final int rounding) {
        if (bd != null && scale != null) {
            return bd.setScale(scale, rounding);
        }
        return null;
    }
}

Related

  1. roundHalfUp2Scale(BigDecimal value)
  2. roundImpl(final BigDecimal number, final int minFractionDigits, final int maxFractionDigits, final RoundingMode mode)
  3. roundingError(final BigDecimal dividend, final BigDecimal divisor, final int roundingMode)
  4. roundOff(final BigDecimal amount)
  5. roundPrice(BigDecimal price, BigDecimal ticksize)
  6. roundToMSDecimal(BigDecimal sourceDecimal)
  7. roundUp1(BigDecimal number)
  8. valueOfBigDecimalRounding(double d1, int decimalPrecision)