如何降低变量的精度?

时间:2013-10-28 18:32:20

标签: java floating-point precision

我想生成30到80之间的数字,并且我使用:

this.length=(float)(Math.random()*50+30);

然后我必须将实例的一些参数解析为string:

result=this.name+" by "+this.smith+" in "+this.productionYear+" at "+this.length+" length";

它生成如下字符串:

  

Lao Che by Youta于1327年以75.341866的长度

我如何截断长度以获得更少的小数精度?我想在点后设置为2位数。

1 个答案:

答案 0 :(得分: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