如何在java中打印带有2个小数位的String

时间:2017-12-01 17:08:26

标签: java string

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

这是我的Java代码。我在s4变量中接受了我的表达式的答案,之后我想将它修复为仅2位小数。由于我的答案是在String数据类型中,我使用String.format()方法,但它不起作用。以前我使用过DecimalFormat对象但它没用,因为我的答案是在String中。没有String.format()方法的代码工作正常。任何人都可以解决这个问题吗?

2 个答案:

答案 0 :(得分:0)

替换

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

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

答案 1 :(得分:0)

您有ClassCastException和IllegalArgumentException 我改变了这两行代码并且它可以工作:

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