当前位置: 移动技术网 > IT编程>开发语言>Java > 如何使用BigDecimal实现Java开发商业计算

如何使用BigDecimal实现Java开发商业计算

2020年09月22日  | 移动技术网IT编程  | 我要评论
前言今天群里一个初级开发者问为什么测试人员测出来他写的价格计算模块有计算偏差的问题,他检查了半天也没找出问题。这里小胖哥要提醒你,商业计算请务必使用bigdecimal,浮点做商业运算是不精确的。因为

前言

今天群里一个初级开发者问为什么测试人员测出来他写的价格计算模块有计算偏差的问题,他检查了半天也没找出问题。这里小胖哥要提醒你,商业计算请务必使用bigdecimal,浮点做商业运算是不精确的。因为计算机无法使用二进制小数来精确描述我们程序中的十进制小数。《effective java》在第48条也推荐“使用bigdecimal来做精确运算”。今天我们就来总结归纳其相关的知识点。

bigdecimal

bigdecimal表示不可变的任意精度带符号十进制数。它由两部分组成:

  • intval - 未校正精度的整数,类型为biginteger
  • scale - 一个32位整数,表示小数点右边的位数

例如,bigdecimal 3.14的未校正值为314,缩放为2。我们使用bigdecimal进行高精度算术运算。我们还将它用于需要控制比例和舍入行为的计算。如果你的计算是商业计算请务必使用计算精确的bigdecimal 。

构造bigdecimal实例

我们可以从string,character 数组,int,long和biginteger创建一个bigdecimal对象:

@test
public void thevaluematches() {
  bigdecimal bdfromstring = new bigdecimal("0.12");
  bigdecimal bdfromchararray = new bigdecimal(new char[]{'3', '.', '1', '4', '1', '5'});
  bigdecimal bdlfromint = new bigdecimal(42);
  bigdecimal bdfromlong = new bigdecimal(123412345678901l);
  biginteger biginteger = biginteger.probableprime(100, new random());
  bigdecimal bdfrombiginteger = new bigdecimal(biginteger);
  assertequals("0.12", bdfromstring.tostring());
  assertequals("3.1415", bdfromchararray.tostring());
  assertequals("42", bdlfromint.tostring());
  assertequals("123412345678901", bdfromlong.tostring());
  assertequals(biginteger.tostring(), bdfrombiginteger.tostring());
}

我们还可以从double创建bigdecimal:

@test
public void whenbigdecimalcreatedfromdouble_thenvaluemaynotmatch() {
  bigdecimal bdfromdouble = new bigdecimal(0.1d);
  assertnotequals("0.1", bdfromdouble.tostring());
}

我们发现在这种情况下,结果与预期的结果不同(即0.1)。这是因为:这个转换结果是double的二进制浮点值的精确十进制表示,其值得结果不是我们可以预测的.我们应该使用string构造函数而不是double构造函数。另外,我们可以使用valueof静态方法将double转换为bigdecimal 或者直接使用其未校正数加小数位数 :

@test
public void whenbigdecimalcreatedusingvalueof_thenvaluematches() {
    bigdecimal bdfromdouble = bigdecimal.valueof(0.1d);
    bigdecimal bigfromlong=bigdecimal.valueof(1,1);

    assertequals("0.1", bdfromdouble.tostring());
    assertequals("0.1", bigfromlong.tostring());
}

在转换为bigdecimal之前,此方法将double转换为其string表示形式。此外,它可以重用对象实例。因此,我们应该优先使用valueof方法来构造函数。

常用api

方法名 对应方法相关用法解释
abs() 绝对值,scale不变
add(bigdecimal augend) 加,scale为augend和原值scale的较大值
subtract(bigdecimal augend) 减,scale为augend和原值scale的较大值
multiply(bigdecimal multiplicand) 乘,scale为augend和原值scale的和
divide(bigdecimal divisor) 除,原值/divisor,如果不能除尽会抛出异常,scale与原值一致
divide(bigdecimal divisor, int roundingmode) 除,指定舍入方式,scale与原值一致
divide(bigdecimal divisor, int scale, int roundingmode) 除,指定舍入方式和scale
remainder(bigdecimal divisor) 取余,scale与原值一致
divideandremainder(bigdecimal divisor) 除法运算后返回一个数组存放除尽和余数 如 23/3 返回 {7,2}
dividetointegralvalue(bigdecimal divisor) 除,只保留整数部分,但scale仍与原值一致
max(bigdecimal val) 较大值,返回原值与val中的较大值,与结果的scale一致
min(bigdecimal val) 较小值,与结果的scale一致
movepointleft(int n) 小数点左移,scale为原值scale+n
movepointright(int n) 小数点右移,scale为原值scale+n
negate() 取反,scale不变
pow(int n) 幂,原值^n,原值的n次幂
scalebypoweroften(int n) 相当于小数点右移n位,原值*10^n

bigdecimal操作

bigdecimal上的操作就像其他number类(integer,long,double等)一样,bigdecimal提供算术和比较操作的操作。它还提供了缩放操作,舍入和格式转换的操作。它不会使算术运算符(+ - /*)或逻辑运算符(> < | &) 过载。相反,我们使用bigdecimal相应的方法 - 加,减,乘,除和比较。并且bigdecimal具有提取各种属性的方法。

提取属性

精度,小数位数和符号:

@test
public void whengettingattributes_thenexpectedresult() {
  bigdecimal bd = new bigdecimal("-12345.6789");

  assertequals(9, bd.precision());
  assertequals(4, bd.scale());
  assertequals(-1, bd.signum());
}

比较大小

我们使用compareto方法比较两个bigdecimal的值:

@test
public void whencomparingbigdecimals_thenexpectedresult() {
  bigdecimal bd1 = new bigdecimal("1.0");
  bigdecimal bd2 = new bigdecimal("1.00");
  bigdecimal bd3 = new bigdecimal("2.0");

  asserttrue(bd1.compareto(bd3) < 0);
  asserttrue(bd3.compareto(bd1) > 0);
  asserttrue(bd1.compareto(bd2) == 0);
  asserttrue(bd1.compareto(bd3) <= 0);
  asserttrue(bd1.compareto(bd2) >= 0);
  asserttrue(bd1.compareto(bd3) != 0);
}

上面的方法在比较时忽略了小数位。如果你既要比较精度又要比较小数位数那么请使用equals方法:

@test
public void whenequalscalled_thensizeandscalematched() {
  bigdecimal bd1 = new bigdecimal("1.0");
  bigdecimal bd2 = new bigdecimal("1.00");

  assertfalse(bd1.equals(bd2));
}

四则运算

bigdecimal 提供了以下四则运算的方法:

  • add ——加法
  • subtract ——减法
  • divide ——除法,有可能除不尽,必须显式声明保留小数位数避免抛出arithmeticexception异常
  • multiply ——乘法
@test
public void whenperformingarithmetic_thenexpectedresult() {
  bigdecimal bd1 = new bigdecimal("4.0");
  bigdecimal bd2 = new bigdecimal("2.0");

  bigdecimal sum = bd1.add(bd2);
  bigdecimal difference = bd1.subtract(bd2);
  bigdecimal quotient = bd1.divide(bd2);
  bigdecimal product = bd1.multiply(bd2);

  asserttrue(sum.compareto(new bigdecimal("6.0")) == 0);
  asserttrue(difference.compareto(new bigdecimal("2.0")) == 0);
  asserttrue(quotient.compareto(new bigdecimal("2.0")) == 0);
  asserttrue(product.compareto(new bigdecimal("8.0")) == 0);
}

四舍五入

既然是数学运算就不得不讲四舍五入。比如我们在金额计算中很容易遇到最终结算金额为人民币22.355的情况。因为货币没有比分更低的单位所以我们要使用精度和舍入模式规则对数字进行剪裁。java提供有两个类控制舍入行为roundingmode和mathcontext 。mathcontext执行的是ieee 754r标准目前不太明白其使用场景,我们使用的比较多的是枚举roundingmode。它提供了八种模式:

roundingmode.up:以小数位为原点 是正数取右边,负数取左边
roundingmode.down:以小数位为原点 也就是正数取左边,负数取右边
roundingmode.floor:取左边最近的正数
roundingmode.ceiling:取右边最近的整数
roundingmode.half_down:五舍六入,负数先取绝对值再五舍六入再负数
roundingmode.half_up:四舍五入,负数原理同上
roundingmode.half_even:这个比较绕,整数位若是奇数则四舍五入,若是偶数则五舍六入
roundingmode.round_unnecessary:不需要取整,如果存在小数位,就抛arithmeticexception 异常

格式化

数字格式化可通过操作类java.text.numberformat和java.text.decimalformat提供的api进行操作。其实我们只需要使用java.text.decimalformat,因为它代理了numberformat。我们来看一下它们的api:

numberformat

numberformat.getinstance(locale)、getnumberinstance(locale)。返回指定语言环境的通用数值格式。
numberformat.getcurrencyinstance(locale)。返回指定语言环境的货币格式。
numberformat.getpercentinstance(locale)。返回指定语言环境的百分比格式。
numberformat.getintegerinstance(locale)。返回指定语言环境的整数数值格式。
numberformat.setminimumintegerdigits(int)。设置数的整数部分所允许的最小位数。
numberformat.setmaximumintegerdigits(int)。设置数的整数部分所允许的最大位数。
numberformat.setminimumfractiondigits(int)。设置最少小数点位数,不足的位数以0补位,超出的话按实际位数输出。
numberformat.setmaximumfractiondigits(int)。设置最多保留小数位数,不足不补0。

decimalformat

decimalformat除了能代理上面的numberformat以外,还提供了基于pattern字符串的格式化风格,有点类似格式化时间一样。我们来看看pattern的规则:

  • “0”——表示一位数值,如没有,显示0。如“0000.0000”,整数位或小数位>4,按实际输出,<4整数位前面补0小数位后面补0,凑足4位。
  • “#”——表示任意位数的整数。如没有,则不显示。在小数点位使用,只表示一位小数,超出部分四舍五入。如:“#”:无小数,小数部分四舍五入。“.#”:整数部分不变,一位小数,四舍五入。“.##”:整数部分不变,二位小数,四舍五入。
  • “.”——表示小数点。注意一个pattern中只能出现一次,超过一次将格式化异常。
  • “,”——与模式“0”一起使用,表示逗号。注意一定不能在小数点后用,否则格式化异常。

总结

今天对bigdecimal进行了总结归纳,这篇文章建议你收藏备用,也可以转给其他需要的同学。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网