//四舍五入
double d=Math.round(4.5);
d=5
//变量按规定的小数位转化
double d=12.2544;
java.text.DecimalFormat df=new java.text.DecimalFormat("###,##0.00");
String g=df.format(d);
System.out.println(g);
或
public static String formatNumber(double f)
{
DecimalFormat df=new DecimalFormat("0.00#");
return df(f);
}
这样就好了!
double d=Math.round(4.5);
d=5
//变量按规定的小数位转化
double d=12.2544;
java.text.DecimalFormat df=new java.text.DecimalFormat("###,##0.00");
String g=df.format(d);
System.out.println(g);
或
public static String formatNumber(double f)
{
DecimalFormat df=new DecimalFormat("0.00#");
return df(f);
}
这样就好了!
保证精度的同时要求四舍五入:
double f = 34.232323;
BigDecimal b = new BigDecimal(f);
double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
0A
// b.setScale(2, BigDecimal.ROUND_HALF_UP) 表明四舍五入,保留两位小数,想保留几位将数字2该动就行
上面是对double类型的处理,如果对float的,则将上面所有的double字段换成float就行方法2:
float scale;
DecimalFormat fnum = new DecimalFormat("##0.00");//保留两位小数
String dd=fnum.format(scale);
System.out.println(dd);
==============================================================
如上所言,并非完全正确,请从建议的角度、用怀疑的眼光批判地接收
Math.round(2.4); // =2
import java.text.DecimalFormat;
public static String roundUp(double d, String RoundFormat)
{
DecimalFormat nf = new DecimalFormat(RoundFormat);
return nf.format(d);
}
parseDouble(String s)
如果是两位小数:
double f = 10.66666667;
f=Double.parseDouble(roundUp(f,"0.00"));
f-->10.67
这样你想保留几位小都可以
f=Double.parseDouble(roundUp(f,"0.0000"));
-f---->10.6667
f=Double.parseDouble(roundUp(f,"0.00000"));
-f---->10.66667
double a=3.2222
a=Math.round(a*100)/100d;
System.out.println(a);