java高精度数字
在使用基本数据类型进行运算的时候,经常会出现结果不准确的情况,于是引入高进度数字类型
float f1 = 123.01f + 2.01f;
System.out.println(f1);
System.out.println(123.01 + 2.01);
int i = Integer.MAX_VALUE;
System.out.println(i * 2);
控制台结果
125.020004
125.02000000000001
-2
BigInterge
BigInteger bigInteger1 = new BigInteger("125");
BigInteger bigInteger2 = new BigInteger("999");
BigInteger result;
// 相加
result = bigInteger1.add(bigInteger2);
System.out.println(bigInteger1 + " + " + bigInteger2 + " = " +result);
// 相减
result = bigInteger2.subtract(bigInteger1);
System.out.println(bigInteger2 + " - " + bigInteger1 + " = " +result);
// 相乘
result = bigInteger1.multiply(bigInteger2);
System.out.println(bigInteger1 + " * " + bigInteger2 + " = " +result);
// 相除
result = bigInteger2.divide(bigInteger1);
System.out.println(bigInteger2 + " / " + bigInteger1 + " = " +result);
// 取余
result = bigInteger2.remainder(bigInteger1);
System.out.println(bigInteger2 + " % " + bigInteger1 + " = " +result);
// 求次方
result = bigInteger1.pow(2);
System.out.println(bigInteger1 + "的2次方是 " + result);
控制台输出
==================================
125 + 999 = 1124
999 - 125 = 874
125 * 999 = 124875
999 / 125 = 7
999 % 125 = 124
125的2次方是 15625
BigDecimal
BigDecimal bigDecimal1 = new BigDecimal(123.01).setScale(5,5);
BigDecimal bigDecimal2 = new BigDecimal(2.01).setScale(5,5);
BigDecimal result;
// 相加
result = bigDecimal1.add(bigDecimal2).setScale(5,5);
System.out.println(bigDecimal1 + " + " + bigDecimal2 + " = " +result);
// 相减
result = bigDecimal1.subtract(bigDecimal2).setScale(5,5);
System.out.println(bigDecimal1 + " - " + bigDecimal2 + " = " +result);
// 相乘
result = bigDecimal1.multiply(bigDecimal2).setScale(5,5);
System.out.println(bigDecimal1 + " * " + bigDecimal2 + " = " +result);
// 相除
result = bigDecimal1.divide(new BigDecimal(2)).setScale(5,5);
System.out.println(bigDecimal1 + " / 2" + " = " +result);
// 取余
result = bigDecimal1.remainder(bigDecimal2).setScale(5,5);
System.out.println(bigDecimal1 + " % " + bigDecimal2 + " = " +result);
// 求次方
result = bigDecimal1.pow(2).setScale(5,5);;
System.out.println(bigDecimal1 + "的2次方是 " + result);
控制台输出
==================================
123.01000 + 2.01000 = 125.02000
123.01000 - 2.01000 = 121.00000
123.01000 * 2.01000 = 247.25010
123.01000 / 2 = 61.50500
123.01000 % 2.01000 = 0.40000
123.01000的2次方是 15131.46010
网友评论