Java BigDecimal Round round(BigDecimal value, int accuracy)

Here you can find the source of round(BigDecimal value, int accuracy)

Description

This method is used for arbitrary accuracy rounding.

License

Open Source License

Parameter

Parameter Description
value is the value to be rounded.
accuracy is the accuracy of the requested rounding. A value greater 0 is the number of digits after the decimal sign. A value less than 0 rounds the number of digits before the decimal sign to zero.

Return

The rounded value is returned.

Declaration

public static BigDecimal round(BigDecimal value, int accuracy) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    /**//from  ww  w.  j a v  a 2 s.c o  m
     * This method is used for arbitrary accuracy rounding.
     * 
     * @param value
     *            is the value to be rounded.
     * @param accuracy
     *            is the accuracy of the requested rounding. A value greater 0
     *            is the number of digits after the decimal sign. A value less
     *            than 0 rounds the number of digits before the decimal sign to
     *            zero.
     * @return The rounded value is returned.
     */
    public static double round(double value, int accuracy) {
        double factor = Math.pow(10.0, accuracy);
        return Math.round(value * factor) / factor;
    }

    /**
     * This method is used for arbitrary accuracy rounding.
     * 
     * @param value
     *            is the value to be rounded.
     * @param accuracy
     *            is the accuracy of the requested rounding. A value greater 0
     *            is the number of digits after the decimal sign. A value less
     *            than 0 rounds the number of digits before the decimal sign to
     *            zero.
     * @return The rounded value is returned.
     */
    public static BigDecimal round(BigDecimal value, int accuracy) {
        MathContext context = new MathContext(accuracy, RoundingMode.HALF_EVEN);
        BigDecimal factor = BigDecimal.valueOf(10.0).pow(accuracy);
        return value.multiply(factor).round(context).divide(factor);
    }
}

Related

  1. round(BigDecimal number)
  2. round(BigDecimal v, int scale, int roundingMode)
  3. round(BigDecimal value)
  4. round(BigDecimal value)
  5. round(BigDecimal value, BigDecimal increment, RoundingMode roundingMode)
  6. round(BigDecimal value, int places)
  7. round(BigDecimal value, String currency)
  8. round(BigDecimal what, int howmuch)
  9. round(final BigDecimal input, final int precision)