Java BigInteger和BigDecimal

java.math 包中的两个很有用的类:Biglnteger 和 BigDecimal
这两个类可以处理包含任意长度数字序列的数值。
Biglnteger 类实现了任意精度的整数运算, BigDecimal 实现了任意精度的浮点数运算。

BigInteger
使用静态的 valueOf方法可以将普通的数值转换为大数值,但是不能使用熟悉的算术运算符(如:+ 和 *) 处理大数值。 而需要使用大数值类中的 add 和 multiply 方法。

BigInteger a = BigInteger.valueof(100);
BigInteger b = BigInteger.valueof(20);
BigInteger c = a.add(b); // c = a + b
Biglnteger d = c.multiply(b.add(BigInteger.valueOf(2))); // d = c * (b + 2)
// b += a; // false
// b += 2; // false
BigInteger方法:
Biglnteger add(Biglnteger other)
Biglnteger subtract(Biglnteger other)
Biglnteger multipiy(BigInteger other)
Biglnteger divide(Biglnteger other)
Biglnteger mod(Biglnteger other)余数
int compareTo(Biglnteger other)相等, 返回 0; 比other小 返回-1; 比other大 返回1。
static Biglnteger valueOf(long x)返回值等于 x 的大整数。
int x = a.compareTo(b);
System.out.println(x); // 1

int y = b.compareTo(a);
System.out.println(y); // -1

BigInteger z = BigInteger.valueOf(5);
System.out.println(z); // 5

BigDecimal

BigDecimal方法:
• BigDecimal add(BigDecimal other)
• BigDecimal subtract(BigDecimal other)
• BigDecimal multipiy(BigDecimal other)
• BigDecimal divide(BigDecimal other, RoundingMode mode)计算商, 必须给出舍入方式 ( 输入RoundingMode)。 如:RoundingMode.HALFUP 是四舍五入。它适用于常规的计算。
• int compareTo(BigDecimal other)相等,返回 0 ; 小于other,返回-1;大于other,返回1。
• static BigDecimal valueOf(long x)返回值为 x 的一个大实数。
• static BigDecimal valueOf(long x ,int scale)返回值为 x / (10^scale) 的一个大实数。
RoundingMode
RoundingMode.UP上取整
RoundingMode.DOWN去掉小数部分取整,也就是正数取左边,负数取右边,相当于向原点靠近的方向取整
RoundingMode.CEILING取右边最近的整数
RoundingMode.FLOOR取左边最近的正数
RoundingMode.HALF_UP四舍五入,负数原理同上
RoundingMode.HALF_DOWN五舍六入,负数先取绝对值再五舍六入再负数
RoundingMode.HALF_EVEN这个比较绕,整数位若是奇数则四舍五入,若是偶数则五舍六入

不同取整模式下的取整操作总结

操作数UPDOWNCEILINGFLOORHALF_UPHALF_DOWNHALF_EVENUNNECESSARY
5.56565656throw ArithmeticException
2.53232322throw ArithmeticException
1.62121222throw ArithmeticException
1.12121111throw ArithmeticException
1.011111111
-1.0-1-1-1-1-1-1-1-1
-1.1-2-1-1-2-1-1-1throw ArithmeticException
-1.6-2-1-1-2-2-2-2throw ArithmeticException
-2.5-3-2-2-3-3-2-2throw ArithmeticException
-5.5-6-5-5-6-6-5-6throw ArithmeticException
BigDecimal a = new BigDecimal("5.677");
BigDecimal b = new BigDecimal("3.0");
BigDecimal c = a.divide(b,RoundingMode.HALF_UP); // 1.892

保留小数方式:setScale(int num,RoundingMode)

BigDecimal d = a.setScale(2,RoundingMode.HALF_UP);// 5.68

BigDecimal的scale函数返回小数位数。

int x = d.scale();// 返回小数的位数,这里返回3
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Brave Seeker

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值