How JAVA calculates string formula

Solution 1: Use commons-jexl3 jar package

You can use the commons-jexl3jar package, which provides some methods for calculating the formula in the string.
maven depends on the following:

<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-jexl3</artifactId>
	<version>3.1</version>
</dependency>

Sample code:

	@Test
    public void test03() {
    
    
        String expressionString = "27.0/10";
        JexlEngine jexlEngine = new JexlBuilder().create();
        JexlExpression jexlExpression = jexlEngine.createExpression(expressionString);
        Object evaluate = jexlExpression.evaluate(null);
        System.out.println(evaluate);
    }

The calculation result is as follows: to prevent loss of precision, at least one precision value must exist in the calculation formula. If you can use the string replacement method replaceAll to replace a certain value in the formula as a precision value, so that there will be no loss of precision.
Insert picture description here

Solution 2: Use the JDK bottom layer to call the calculation formula of javaScript (recommended)

The class that comes with the JDK can implement the function of calling JS and the function of executing the calculation formula in the string. The sample code is as follows:

	@Test
    public void test04() throws ScriptException {
    
    
        ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
        String strs = "27/10";
        System.out.println(jse.eval(strs));
    }

The results are as follows: using this scheme can directly avoid the loss of precision, if there are variables in the formula as the elements of the operation, you can use the replaceAll method of the string to replace.
Insert picture description here
The sample code of the replacement method is as follows:

	@Test
    public void test04() throws ScriptException {
    
    
        ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
        String strs = "1+b";
        strs = strs.replace("b", "9");
        System.out.println(jse.eval(strs));
    }

Guess you like

Origin blog.csdn.net/qq_43647359/article/details/107821763