Here you can find the source of getEfficientRound(BigDecimal val, int effectiveDigit)
Parameter | Description |
---|---|
value | The target value |
effectiveDigit | Significant figure digit number |
public static String getEfficientRound(BigDecimal val, int effectiveDigit)
//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(); } }