float f = 2.2f; System.out.println(f); System.out.println(Double.valueOf(f)); System.out.println(new BigDecimal(f)); System.out.println(new BigDecimal(String.valueOf(f))); System.out.println(new BigDecimal(String.valueOf(f)).doubleValue()); 2.2 2.200000047683716 2.2000000476837158203125 2.2 2.2
double d = 0.1d; System.out.println(d); System.out.println(d + 0.05d); System.out.println(new BigDecimal(String.valueOf(d)).add(new BigDecimal("0.05"))); System.out.println(new BigDecimal(String.valueOf(d)).add(new BigDecimal("0.05")).doubleValue()); 0.1 0.15000000000000002 0.15 0.15
String number = "123.12545"; System.out.println(Double.valueOf(number)); System.out.println(Double.valueOf(number).intValue()); System.out.println(new BigDecimal(number).intValue()); 123.12545 123 123
String number = "123.12545"; System.out.println(new BigDecimal(number).setScale(2, BigDecimal.ROUND_HALF_UP)); System.out.println(new BigDecimal(number).setScale(2, BigDecimal.ROUND_DOWN)); System.out.println(String.format("%.2f", new BigDecimal(number))); 123.13 123.12 123.13
BigDecimal b = new BigDecimal("0.00"); BigDecimal zero = new BigDecimal("0"); System.out.println(b.equals(zero)); System.out.println(b.equals(zero.setScale(2))); false true equals()會比較精度 比較數值用:compareTo BigDecimal.valueOf(1).compareTo(BigDecimal.valueOf(2)) == 0
高精度的計算須要將數據轉成String,再將String轉成BigDecimal,用BigDecimal進行計算.spa