1.
public class BigDecimalTest { public static void add(double d1,double d2){ BigDecimal b1 = new BigDecimal(d1); BigDecimal b2 = new BigDecimal(d2); double result = b1.add(b2).doubleValue(); int result2 = b1.add(b2).intValue(); System.out.println(result); } public static void sub(double d1, double d2){ BigDecimal b1 = new BigDecimal(d1); BigDecimal b2 = new BigDecimal(d2); double result = b1.subtract(b2).doubleValue();//7.2219999999999995 System.out.println(result); } public static void multiply (double d1, double d2){ BigDecimal b1 = new BigDecimal(d1); BigDecimal b2 = new BigDecimal(d2); double result = b1.multiply(b2).doubleValue(); System.out.println(result); } public static void divide (double d1, double d2,int len){ BigDecimal b1 = new BigDecimal(d1); BigDecimal b2 = new BigDecimal(d2); double result = b1.divide(b2,len,BigDecimal.ROUND_HALF_UP).doubleValue();//BigDecimal.ROUND_HALF_UP 四舍五入 System.out.println(result); } private static void getTotalPages(double d1,double d2){ BigDecimal b1 = new BigDecimal(d1); BigDecimal b2 = new BigDecimal(d2); int totalPage = b1.divide(b2,0,BigDecimal.ROUND_UP).intValue();//小数点后保留0位, 小数点位置非0加一 System.out.println(totalPage); } public static void main(String[] args) { add(10.333,3.111);//13.444 sub(10.333,3.111);//7.2219999999999995 multiply(10.333,3.111);//32.145963 divide(10.0,3.0,1);//3.3 divide(10.0,3.0,2);//3.33, len代表小数点后面几位 BigDecimal.ROUND_HALF_UP divide(10.0,3.0,3);//3.333, len代表小数点后面几位 divide(10.0,3.0,4);//3.3333 getTotalPages(100,30);//总记录是100跳每页要有30条记录,总共多少页? 4页! } } public int getTotalPage() { if(perpage>0){ BigDecimal b1 = new BigDecimal(totalCount); BigDecimal b2 = new BigDecimal(perpage); totalPage = b1.divide(b2,0,BigDecimal.ROUND_UP).intValue(); return totalPage; }else{ return 0; } }
2. Bigdecimal 与 NumberFormat
public class NumberFormatDemo { public static void main(String[] args) { NumberFormat currency = NumberFormat.getCurrencyInstance(); NumberFormat percent = NumberFormat.getPercentInstance(); percent.setMinimumFractionDigits(2);//百分比后三位 BigDecimal loanAmout = new BigDecimal("15000.8"); BigDecimal interestRate = new BigDecimal("0.008"); BigDecimal interest = loanAmout.multiply(interestRate); System.out.println("贷款金额: "+ currency.format(loanAmout)); System.out.println("利率: "+percent.format(interestRate)); System.out.println("利息: "+currency.format(interest)); } /* 贷款金额: ¥15,000.80 利率: 0.80% 利息: ¥120.01 */ }