BigDecimal的使用

BigDecimal的使用

基本计算方法

  • multiply()
  • divide()
  • add()
  • subtract()

保留小数点位数

/*
** 使用BigDecimal这个方法
*@param newScale 小数点位数
* @param roundingMode 舍去方式
* @return
*/
public BigDecimal setScale(int newScale, RoundingMode roundingMode) {
return setScale(newScale, roundingMode.oldMode);
}
/**
 * 除法也可以直接在计算是传入参数保留小数点
 * @param divisor 除数
 * @param scale 小数点位数
 * @param roundingMode 舍去方式
 * @return
 */
public BigDecimal divide(BigDecimal divisor, int scale, RoundingMode roundingMode) {
	return divide(divisor, scale, roundingMode.oldMode);
}
RoundingMode的几个形式
  • HALF_UP 四舍五入,即,值>=0.5,入,否则舍去

  • CEILING 值向上取整,值变大

  • FLOOR 值向下取整,值变小

  • HALF_DOWN 绝对值 >0.5 ,才入,否则舍去。

  • HALF_EVEN ,

    • 如果丢弃的分数左边的数字是奇数,则表现与HALF_UP相同;
    • 如果是偶数,其行为与HALF_DOWN相同。
  • UP 绝对值向上取整,正数变大,负数变小

  • DOWN 绝对值向下取整,正数变小,负数变大

  • ROUND_UNNECESSARY, 舍入模式断言所请求的操作具有精确的结果,因此不需要舍入。如果在产生不精确结果的操作上指定此舍入模式,则会引发ArithmeticException 。

Summary of Rounding Operations Under Different Rounding Modes
Result of rounding input to one digit with the given rounding mode
Input Number{@code UP}{@code DOWN}{@code CEILING}{@code FLOOR}{@code HALF_UP}{@code HALF_DOWN}{@code HALF_EVEN}{@code UNNECESSARY}
5.56565656throw {@code ArithmeticException}
2.53232322throw {@code ArithmeticException}
1.62121222throw {@code ArithmeticException}
1.12121111throw {@code ArithmeticException}
1.011111111
-1.0-1-1-1-1-1-1-1-1
-1.1-2-1-1-2-1-1-1throw {@code ArithmeticException}
-1.6-2-1-1-2-2-2-2throw {@code ArithmeticException}
-2.5-3-2-2-3-3-2-2throw {@code ArithmeticException}
-5.5-6-5-5-6-6-5-6throw {@code ArithmeticException}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值