public static void main(String[] args) { BigDecimal big = new BigDecimal("68"); BigDecimal reuturn = sqrt(big,2); String result = reuturn.stripTrailingZeros().toPlainString(); System.out.println("result= "+result);//8.25 } /** * * @Title: sqrt * @Description: TODO 计算开方 * @param value 要计算的数字 * @param scale 保留多少小数位 * @return * @Author:wushigao * @CreateDate:2022年10月10日 下午2:34:09 */ public static BigDecimal sqrt(BigDecimal value, int scale){ BigDecimal num2 = BigDecimal.valueOf(2); int precision = 100; MathContext mc = new MathContext(precision, RoundingMode.HALF_UP); BigDecimal deviation = value; int cnt = 0; while (cnt < precision) { deviation = (deviation.add(value.divide(deviation, mc))).divide(num2, mc); cnt++; } deviation = deviation.setScale(scale, BigDecimal.ROUND_HALF_UP); return deviation; }
标签:deviation,cnt,BigDecimal,int,value,result,计算,开方 From: https://www.cnblogs.com/wwssgg/p/16775780.html