java math四舍五入保留两位小数
使用 DecimalFormat 类:
double num = 3.14159;
DecimalFormat df = new DecimalFormat(“#.##”);
double roundedNum = Double.parseDouble(df.format(num));
System.out.println(roundedNum);
使用 BigDecimal 类:
double num = 3.14159;
BigDecimal bd = new BigDecimal(num);
BigDecimal roundedNum = bd.setScale(2, RoundingMode.HALF_UP);
System.out.println(roundedNum);
使用 Math 类:
double num = 3.14159;
double roundedNum = Math.round(num * 100) / 100.0;
System.out.println(roundedNum);
使用 String.format 方法:
double num = 3.14159;
String roundedNum = String.format(“%.2f”, num);
System.out.println(roundedNum);
使用 NumberFormat 类:
double num = 3.14159;
NumberFormat nf = NumberFormat.getNumberInstance();
nf.setMaximumFractionDigits(2);
String roundedNum = nf.format(num);
System.out.println(roundedNum);
微信赞赏
支付宝扫码领红包