Formula calculation + digit retention

1. Enter a calculation formula such as: a+b/c

2. Bring in the formula for calculation

3. Keep the number of decimal places

code show as below:

public static Object cal(String str) {

    ScriptEngineManager manager = new ScriptEngineManager();  

    ScriptEngine engine = manager.getEngineByName("js");  

    Object result=null;

    try {

        result = engine.eval(str);

    } catch (ScriptException e) {

        e .printStackTrace ();

    } 

    System.out .println ( "Result type: " + result .getClass ().getName() + ", calculation result: " + result ); 

    return result;

}

public static void main(String[] args) {

    Map<String,Object> map = new HashMap<String,Object>();

    map.put("a", 1);

    map.put("b", 2);

    map.put("c", 3);

    String s = "a,b,c";

    String[] strSplit = s.split(",");

    String str = "(b-a)/c";

    //replace the variables in the formula with numbers

    for ( int i = 0; i < strSplit . length ; i ++) {

        str = str.replaceAll(strSplit[i], map.get(strSplit[i]).toString());

    }

    // Calculate after replacing with numbers

    Object obj = cal(str);

    //After the calculation, it is an Object type with multiple N decimals. String.format() is the reserved number of digits and rounding. 

    System.out.println(String.format("%.2f",obj));

}




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325854919&siteId=291194637