Math类
package ch7;
public class MathDemo {
public static void main(String[] args) {
System.out.println("Math.floor(-1.2):"+Math.floor(-1.2));
System.out.println("Math.ceil(1.2):"+Math.ceil(1.2));
System.out.println("Math.round(2.3):" +Math.round(2.3));
System.out.println("Math.max(2.3,4.5):"+Math.max(2.3,4.5));
System.out.println("Math.min(2.3,4.5):"+Math.min(2.3,4.5));
System.out.println("Math.random():"+Math.random());
}
}
BigDecimal
package ch7;
import java.math.BigDecimal;
public class BigDecimalDemo {
public static void main(String[] args) {
System.out.println("0.05 + 0.01 = " + (0.05 + 0.01));
System.out.println("1.0 - 0.42 = " + (1.0 - 0.42));
System.out.println("4.015 * 100 = " + (4.015 * 100));
System.out.println("123.3 / 100 = " + (123.3 / 100));
BigDecimal f1 = new BigDecimal("0.05");
BigDecimal f2 = BigDecimal.valueOf(0.01);
BigDecimal f3 = new BigDecimal(0.05);
System.out.println("使用String作为BigDecimal构造器参数:");
System.out.println("0.05 + 0.01 = " + f1.add(f2));
System.out.println("0.05 - 0.01 = " + f1.subtract(f2));
System.out.println("0.05 * 0.01 = " + f1.multiply(f2));
System.out.println("0.05 / 0.01 = " + f1.divide(f2));
System.out.println("使用double作为BigDecimal构造器参数:");
System.out.println("0.05 + 0.01 = " + f3.add(f2));
System.out.println("0.05 - 0.01 = " + f3.subtract(f2));
System.out.println("0.05 * 0.01 = " + f3.multiply(f2));
System.out.println("0.05 / 0.01 = " + f3.divide(f2));
}
}
衍生出来的工具类Arith
package ch7;
import java.math.BigDecimal;
import java.util.function.BinaryOperator;
public class Arith {
private static final int DEF_DIV_SCALE = 10;
private Arith() {}
public static double add(double v1,double v2) {
BigDecimal b1 = BigDecimal.valueOf(v1);
BigDecimal b2 = BigDecimal.valueOf(v2);
return b1.add(b2).doubleValue();
}
public static double sub(double v1,double v2) {
BigDecimal b1 = BigDecimal.valueOf(v1);
BigDecimal b2 = BigDecimal.valueOf(v2);
return b1.subtract(b2).doubleValue();
}
public static double mul(double v1,double v2) {
BigDecimal b1 = BigDecimal.valueOf(v1);
BigDecimal b2 = BigDecimal.valueOf(v2);
return b1.multiply(b2).doubleValue();
}
public static double div(double v1,double v2) {
BigDecimal b1 = BigDecimal.valueOf(v1);
BigDecimal b2 = BigDecimal.valueOf(v2);
return b1.divide(b2,DEF_DIV_SCALE,BigDecimal.ROUND_HALF_UP).doubleValue();
}
public static void main(String[] args) {
System.out.println("0.05 + 0.01= " + Arith.add(0.05,0.01));
System.out.println("1.0 - 0.42= " + Arith.sub(1.0,0.42));
System.out.println("4.015 * 100= " + Arith.mul(4.015,100));
System.out.println("123.3 / 1000= " + Arith.div(123.3,1000));
}
}
本文转自TBHacker博客园博客,原文链接:http://www.cnblogs.com/jiqing9006/p/6096213.html,如需转载请自行联系原作者