保留小数点(四舍五入)java

public class Decimal {
public static void main(String[] args) {
	double d=6.666;
	//1、只是用来打印输出,这种最方便,会自动四舍五入。%.2f表示保留2位小数,同理%.1f,%.3f
	System.out.println(String.format("%.2f", d));
	
	//2、使用DecimalFormat类
	DecimalFormat df=new DecimalFormat("#.00");
	System.out.println(df.format(d));
	
	//3、不使用任何函数或类,手动转换
	double tmp=(int)(d*100+0.5);
	double res=tmp/100;
	System.out.println(res);
}
}

猜你喜欢

转载自blog.csdn.net/qq_40908515/article/details/86552196