Java BigDecimal Round getEfficientRound(BigDecimal val, int effectiveDigit)

Here you can find the source of getEfficientRound(BigDecimal val, int effectiveDigit)

Description

The numerical value below a significant figure is rounded off.

License

Open Source License

Parameter

Parameter Description
value The target value
effectiveDigit Significant figure digit number

Return

retVal The rounded-off numerical value

Declaration

public static String getEfficientRound(BigDecimal val,
        int effectiveDigit) 

Method Source Code

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

import java.math.BigDecimal;
import java.math.BigInteger;

public class Main {
    /**//w  ww .  j  a v a2 s.com
     * The numerical value below a significant figure is rounded off.
     *
     * @param value The target value
     * @param effectiveDigit Significant figure digit number
     * @return retVal The rounded-off numerical value
     */
    public static String getEfficientRound(BigDecimal val,
            int effectiveDigit) {

        if (effectiveDigit <= 0) {
            return val.toString();
        }

        int intLength = getIntLength(val);
        int delta = intLength - effectiveDigit;

        if (delta > 0) {
            BigDecimal tenPower = new BigDecimal(
                    new BigInteger("10").pow(delta));
            BigDecimal unscaledValue = new BigDecimal(val.unscaledValue());
            BigDecimal bak = unscaledValue.divide(tenPower, 0,
                    BigDecimal.ROUND_HALF_UP).multiply(tenPower);

            BigDecimal tempVal = new BigDecimal(bak.unscaledValue(),
                    val.scale());
            StringBuilder tempStr = new StringBuilder(tempVal.toString());
            StringBuilder reverseStr = new StringBuilder(tempStr.reverse()
                    .substring(delta));
            String retVal = reverseStr.reverse().toString();

            if (retVal.substring(retVal.length() - 1).equals(".")) {
                return retVal.replace(".", "");
            }

            return retVal;
        } else {
            return val.toString();
        }
    }

    /**
     * The digit number of an integer part is acquired.
     *
     * @param val The target value
     * @return length The digit number of an integer portion
     */
    private static int getIntLength(BigDecimal val) {
        BigInteger intVal = val.unscaledValue();
        intVal = intVal.abs();
        String bak = intVal.toString();

        return bak.length();
    }
}

Related

  1. average(int precision, RoundingMode roundingMode, BigDecimal... decimals)
  2. decimalRound(BigDecimal number, int numDigits, RoundingMode rounding)
  3. getRoundedAmt(BigDecimal amtBeforeRnd)
  4. getRoundedBigDecimal(double value)
  5. getRoundedBigDecimal(double value, int scale)
  6. getStringValue(BigDecimal val, int newScale, int roundingMode)