如何在java中打印小数点后两位的字符串

如何在java中打印小数点后两位的字符串,java,string,Java,String,这是我的Java代码。我在s4变量中获取表达式的答案,然后我想将其修正为小数点后2位。因为我的答案是字符串数据类型,所以我使用了String.format()方法,但它不起作用。以前我使用过DecimalFormat对象,但它没有用,因为我的答案是字符串。没有String.format()方法,代码工作正常。有人能解决这个问题吗?更换 Scanner in = new Scanner(System.in); //String s = in.next(); String s1; String x

这是我的Java代码。我在
s4
变量中获取表达式的答案,然后我想将其修正为小数点后2位。因为我的答案是字符串数据类型,所以我使用了String.format()方法,但它不起作用。以前我使用过DecimalFormat对象,但它没有用,因为我的答案是字符串。没有String.format()方法,代码工作正常。有人能解决这个问题吗?

更换

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


您有ClassCastException和IllegalArgumentException 我更改了这两行代码,它可以正常工作:

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

这个问题似乎得到了回答。请稍候,当您执行
s4=(String)engine.eval(s2)
时,您说存在ClassCastException?那个演员是哪个班的?可能是双人房。所以不需要将其更改为String,然后将其解析回double!只需执行
String.format(“%.2f”,(双)引擎.eval(s2))
s5 = String.format("%.2f", Double.parseDouble(s4));
 s4 = "" + engine.eval(s2);
 s5 = String.format("%.2f",Double.parseDouble(s4));