Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
chennxu opened this issue May 14, 2024 · 2 comments
Labels
bug Something isn't working

Comments

@chennxu
Copy link

chennxu commented May 14, 2024

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 chennxu added the bug Something isn't working label May 14, 2024
@BeardedManZhao
Copy link
Owner

的确如此,Java的浮点计算的计算基于二进制浮点数标准(IEEE 754),但这并不是没有办法解决的,感谢您的反馈,我们将会在下一版本开始使用一些手段解决此问题!

@BeardedManZhao
Copy link
Owner

感谢您的反馈哦~ 您可以参考一下:#15

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants