Shahrukh Khan
Shahrukh Khan

Reputation: 3

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?

Upvotes: 0

Views: 162

Answers (2)

Ikigai programmeh
Ikigai programmeh

Reputation: 398

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));

Upvotes: 0

Valdrinium
Valdrinium

Reputation: 1416

Replace

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

with

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

Upvotes: 1

Related Questions