一、取整
1.向下取整:
①强转为 int 类型;
int n = (int) 3.14
②Math.ceil(double num)方法;
double d = Math.ceil(3.14)
2.向上取整:
Math.floor(double num)方法
double d = Math.floor(3.14);
3. 四舍五入保留整数:
Math.round(double num)方法;
int n = Math.round(3.14);
二、小数四舍五入
1.调用String的formate()方法:
double d = 10.2345;
String result = String.format("%.2f",d);
2.使用NumberFormat对象
double d = 10.2345;
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
String s = nf.format(d);
System.out.println("s1="+s);
nf.setMaximumFractionDigits(3);
s = nf.format(d);
System.out.println("s2="+s);