BigDecimal及Integer的转化问题

Integer

Integerint的包装类 。一个 Integer 类型占 4 字节,一个字节占 8 bit,因此一个 Integer 总共占 32 bit。去除第一位的符号位,剩下 31 位来表示数值。

所以Integer的表示范围最小值为 -2^31,最大值为 2^31-1。

BigInteger

大正整数的包装类

创建BigInteger

1.new BigInteger(String val)方式——将十进制字符串表示形式转换为BigInteger

BigInteger bigInteger = new BigInteger("123");

2.new BigInteger(String val,int radix)——将 radix 进制的数据转化为十进制的BigInteger类型的数据

BigInteger bigInteger = new BigInteger("10",16);

如果不指定 radix 则默认是十进制。

BigInteger的运算
BigInteger a = new BigInteger("12");
BigInteger b = new BigInteger("10");

BigInteger add = a.add(b);                //加       22
BigInteger subtract = a.subtract(b);     //减        2
BigInteger multiply = a.multiply(b);     //乘       120
BigInteger divide = a.divide(b);         //除        1
 BigInteger mod = a.mod(b);               //取模      2
BigInteger remainder = a.remainder(b);  //余数       2
BigInteger abs = a.abs();               //绝对值     12
BigInteger的比较大小
int i = a.compareTo(b);                 // a>b 1  a< b -1 a=b 0       
BigInteger max = a.max(b);              //最大值     12
BigInteger min = a.min(b);              //最小值     10

BigDecimal

大浮点数的包装类,继承了BigInteger类,主要用于货币的存储和计算

创建BigDecimal
BigDecimal bigDecimal = new BigDecimal("123"); //string
BigDecimal bigDecimal = new BigDecimal(123); //int
BigDecimal bigDecimal = new BigDecimal(new BigInteger("123")); //BigInteger
运算
BigDecimal a = new BigDecimal("12");
BigDecimal b = new BigDecimal("10");

BigDecimal add = a.add(b);                //加       22
BigDecimal subtract = a.subtract(b);     //减        2
BigDecimal multiply = a.multiply(b);     //乘       120
BigDecimal divide = a.divide(b);         //除        1.2
BigDecimal remainder = a.remainder(b);  //余数       2
BigDecimal abs = a.abs();               //绝对值     12
比较
int i = a.compareTo(b);                 // a>b 1  a< b -1 a=b 0
BigDecimal max = a.max(b);              //最大值     12
BigDecimal min = a.min(b);              //最小值     10
BigDecimal与BigInteger的转换
BigDecimal bigDecimal = new BigDecimal(new BigInteger("123")); //BigInteger

小案例

// 订单总金额
BigDecimal amount = new BigDecimal(0);
//将获取的Integer类型的数据转换成BigDecimal后进行数据的计算
BigDecimal num = new BigDecimal(shoppingCart.getNumber()); 
amount = amount.add(shoppingCart.getAmount().multiply(num));
orderDetails.add(orderDetail);
  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值