Java循环输入至文件结尾
今天有写到java保留两位小数得题目,Java不像c语言printf("%.2f",f);
这样子输出,于是找了下资料找到以下两种方法
- 方法一:使用Math.round()函数,此处返回的是数字格式
float f=1.258;
int i=3;
float t=f*i;
float num=(float)(Math.round(t*100)/100.0);//如果要求精确4位就*10000然后/10000
我用这种方法试了之后发现了一些问题就是:Math.round()函数会四舍五入,若t为3.5则会四舍五入得结果为4.0,float num=(float)(Math.round(t*100)/100.0);
Math.round()返回的是int类型,之前一直是Math.round(t*100)/100);
,代码中的100是整数,结果返回的值只保留一个小数点,但是改位100.0就可以保留任意位小数了。
- 方法二:使用DecimalFormat包,此处返回的是string类型
import java.text.DecimalFormat;
sum = 1.55555 //计算最终分数
DecimalFormat decimalFormat=new DecimalFormat(".00"); //如果小数不足2位,会以0补足.
String p=decimalFormat.format(sum);