1. double保留小数位
public static void main(String[] args) {
double num = 99.32511;
BigDecimal bd = new BigDecimal(num);
String d1 = bd.setScale(2, RoundingMode.DOWN).toString();
System.out.println(d1);
String d2 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
System.out.println(d2);
}
2. double加减乘除
public class Test {
public static void main(String[] args) {
double num = 99.32511;
BigDecimal bd = new BigDecimal(num);
String d1 = bd.setScale(2, RoundingMode.DOWN).toString();
System.out.println(d1);
String d2 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
System.out.println(d2);
Test test = new Test();
System.out.println(test.add(1.1, 2.2));
System.out.println(test.subtract(3.3, 2.2));
System.out.println(test.mul(3.3, 2.2));
System.out.println(test.div(3.3, 2.2, 2));
}
private double add(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.add(b2).doubleValue();
}
private double subtract(double v1, double v2) {
BigDecimal b1 = new BigDecimal(Double.toString(v1));
BigDecimal b2 = new BigDecimal(Double.toString(v2));
return b1.subtract(b2).doubleValue();
}
public double mul(double d1, double d2){
BigDecimal b1 = new BigDecimal(Double.toString(d1));
BigDecimal b2 = new BigDecimal(Double.toString(d2));
return b1.multiply(b2).doubleValue();
}
public double div(double d1,double d2,int len) {
BigDecimal b1 = new BigDecimal(Double.toString(d1));
BigDecimal b2 = new BigDecimal(Double.toString(d2));
return b1.divide(b2, len, BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static int compareTo(double d1, double d2) {
BigDecimal b1 = new BigDecimal(Double.toString(d1));
BigDecimal b2 = new BigDecimal(Double.toString(d2));
return b1.compareTo(b2);
}
}