mathematical-expression icon indicating copy to clipboard operation
mathematical-expression copied to clipboard

【精度丢失】【java 版本好像都有】【含小数数学的表达式】

Open chennxu opened this issue 1 month ago • 2 comments

import com.hy.common.core.exception.entity.BusinessException; import com.hy.common.core.utils.MathUtils; import com.hy.common.core.utils.StringUtils;

import core.Mathematical_Expression; import core.calculation.Calculation; import core.container.CalculationNumberResults;

public class MathematicalUtils {

private static Calculation instance;

public static void main(String[] args) {
	System.out.println(calc("0.3*3", 1, 2));
           // 输出 0.89

}

/**
 * 执行计算数学表达式 结果
 * @param expression 数学表达式 如 3/2+1*4
 * @param holdType 保留方式:1 四舍五入 2 直接截取
 * @param decimalPlaces 小数点位数
 * @return
 */
public static double calc(String expression, Integer holdType, Integer decimalPlaces) {
	expression = expression.replaceAll("÷", "/").replaceAll("×", "*").replaceAll("+", "+").replaceAll("-", "-");
	if(instance == null) {
		instance = Mathematical_Expression.getInstance(Mathematical_Expression.bracketsCalculation2);
	}
	try {
        instance.check(expression);
        CalculationNumberResults calculation = (CalculationNumberResults) instance.calculation(expression);
        double val = calculation.getResult(); // 值为:0.8999999999999999
        if(Double.isInfinite(val)) {
            throw new BusinessException(StringUtils.append("0不能成为被除数,数学表达式:", expression));
        }
        
        if (holdType == 1) {
        	return MathUtils.roundDown(val, decimalPlaces);
		}
        return MathUtils.roundHalfUp(val, decimalPlaces);
    } catch (Exception e) {
        throw new BusinessException(StringUtils.append("数学表达式格式有误:", expression));
    }
}

}

chennxu avatar May 14 '24 04:05 chennxu