Languages: Java
Categories: 编程语言基础
BigDecimal详细使用
public static void main(String[] args) {
BigDecimal bigOne = new BigDecimal("10");
BigDecimal bigTwo = new BigDecimal("2");
BigDecimal bigThree = new BigDecimal("-10.5");

BigDecimal subtract = bigOne.subtract(bigTwo);
System.out.println("求差：" + subtract);

BigDecimal multiply = bigOne.multiply(bigTwo);
System.out.println("乘法：" + multiply);

BigDecimal divide = bigOne.divide(bigTwo);
System.out.println("除法：" + divide);

BigDecimal remainder = bigOne.remainder(bigTwo);
System.out.println("求余：" + remainder);

BigDecimal max = bigOne.max(bigTwo);
System.out.println("最大数：" + max);

BigDecimal min = bigOne.min(bigTwo);
System.out.println("最小数：" + min);

BigDecimal abs = bigThree.abs();
System.out.println("绝对值：" + abs);

BigDecimal negate = bigOne.negate();
System.out.println("相反数：" + negate);

BigDecimal bigFour = new BigDecimal("2");
BigDecimal result1 = bigOne.divide(bigTwo, 2, BigDecimal.ROUND_HALF_UP);
BigDecimal result2 = bigOne.divide(bigFour, 2, BigDecimal.ROUND_HALF_UP);
System.out.println("舍入-除法：" + result1);
System.out.println("舍入-除法：" + result2);

// 保留两位小数
double pai = 3.14159265358;
DecimalFormat df = new DecimalFormat("#.00");
String one = df.format(pai);
System.out.println(pai + "保留三位小数：" + one);

DecimalFormat myformat = new DecimalFormat("0.00");
String two = myformat.format(pai);
System.out.println(pai + "保留两位小数：" + two);

pai = 3.15759265358;
BigDecimal bigDecimal = new BigDecimal(pai);
double three = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
System.out.println(pai + "保留两位小数并四舍五入：" + three);
}