我想生成 30 到 80 之间的数字,为此我使用:
this.length=(float)(Math.random()*50+30);
然后我必须将实例的一些参数解析为字符串:
result=this.name+" by "+this.smith+" in "+this.productionYear+" at "+this.length+" length";
它生成如下所示的字符串:
Lao Che by Youta in 1327 at 75.341866 length
如何截断长度以降低小数精度?我想将其设置为点后 2 位数字。
最佳答案
你可以这样做:
import java.text.DecimalFormat;
double d = 1.234567;
DecimalFormat df = new DecimalFormat("#.##");
System.out.print(df.format(d));
或者尝试:
double d = 1111.234567;
String str_d = String.format("%1$.2f", d); // String.format(...) generates a new String
System.out.println("Result: " + str_d); // Now you can use it like anyother String
关于java - 如何降低变量的精度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19642427/