1、System.out.printf(); (若想保留多位,只需将"%.2f"中的2改为想保留个数)
System.out.println("----------第一种使用Printf打印---------------");
double a = 3.1456;
System.out.printf("%.2f",a);
2、String.format(); (若想保留多位,只需将"%.2f"中的2改为想保留个数)
System.out.println("\n--------第二种使用String的format()方法-------");
String s1 = String.format("%.2f", a);
System.out.println(s1);
3、BigDecimal 中的setScale(2,BigDecimal.ROUND_HALF_UP) 方法 (若想保留多位,只需将参数"2"中的2改为想保留个数)
System.out.println("--------第三种使用BidDecimal的setScale()方法-");
BigDecimal bigDecimal = new BigDecimal(a).setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println(bigDecimal);
4、Math.round()方法(round实质是四舍五入取整,下面原理就是将小数所取位数之前都变为整数之后再除运算)
System.out.println("--------第四种使用Math的round()方法----------");
double round = Math.round(a*100)/100.0;
System.out.println(round);
5、DecimalFormat (若想保留多位"#.##"小数点后面的#个数则代表保留小数个数)
System.out.println("--------第五种使用DecimalFormat--------------");
DecimalFormat df = new DecimalFormat("#.##");
String format = df.format(a);
System.out.println(format);
结果: