简体   繁体   中英

how to print String with 2 decimal places in java

Scanner in = new Scanner(System.in);
//String s = in.next();
String s1;
String x = in.next();
String s2;
String s3= "3*4.4+pow(sqrt(sin(x)),3)";
String s4;
String s5;

s1 = s3.replace("sin(x)","Math.sin(x)").replace("cos(x)","Math.cos(x)").replace("tan(x)","Math.tan(x)").replace("sqrt","Math.sqrt").replace("pow(","Math.pow(");
s2 = s1.replace("x", x);
System.out.println(s2);


ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine engine = mgr.getEngineByName("JavaScript");
s4 = (String) engine.eval(s2);
s5 = String.format("%.2f",s4);

System.out.println(s5);

Here is my Java code. I'm taking the answer of my expression in s4 variable and after that I want to fix it for just 2 decimal places. As my answer is in String data type, I used String.format() method but it is not working. Previously I have used DecimalFormat object but it was useless because my answer is in String. The code working fine without String.format() method. Can anyone fix this?

Replace

s5 = String.format("%.2f",s4);

with

s5 = String.format("%.2f", Double.parseDouble(s4));

You have ClassCastException and IllegalArgumentException I changed these two lines of code and it works:

 s4 = "" + engine.eval(s2);
 s5 = String.format("%.2f",Double.parseDouble(s4));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM