Java08-BigDecimal类的常用方法
金额计算不能用double,金额计算必须用BigDecimal,
import java.math.BigDecimal; import java.math.RoundingMode; public class test_BigDecimal { public static void main(String[] args) { BigDecimal a = new BigDecimal("12.1"); BigDecimal b = new BigDecimal("13.1"); // 加法 BigDecimal c = a.add(b); System.out.println("加法add: " + c); // 减法 System.out.println("减法subtract: " + a.subtract(b)); // 乘法 System.out.println("乘法multiply: " + a.multiply(b)); // 除法-保留小数点后3位 System.out.println("除法divide: " + a.divide(b, 3, RoundingMode.HALF_UP)); // 2个数相比较-1: less than, 0:equal to, 1: greater than System.out.println("compareTo: " +a.compareTo(b)); //true if and only if the specified Object is a BigDecimal whose value and scale are equal to this BigDecimal's. System.out.println("equals: " +a.equals(b)); //Returns the string System.out.println("toString: " +a.toString()); //Converts this BigDecimal to a BigInteger System.out.println("toBigInteger: " +a.toBigInteger()); } }