天天看点

BigDecimal创建初始化值类型对比

当初始化String类型和double类型,入参值相同,对比输出值

​<code>​ ​</code>​

​<code>​BigDecimal bigDecimalStr = new BigDecimal("0.1");​</code>​

​<code>​BigDecimal bigDecimalDou = new BigDecimal(0.1);​</code>​

​<code>​System.out.println("bigDecimalStr: " + bigDecimalStr);​</code>​

​<code>​System.out.println("bigDecimalDou: " + bigDecimalDou);​</code>​

​<code>​System.out.println("bigDecimalStr and bigDecimalDou: " + bigDecimalStr.compareTo(bigDecimalDou));​</code>​

​<code>​ ​</code>​输出结果:

​<code>​bigDecimalStr: 0.1​</code>​

​<code>​bigDecimalDou: 0.1000000000000000055511151231257827021181583404541015625​</code>​

​<code>​bigDecimalStr and bigDecimalDou: -1​</code>​

对比结果,即String类型和double类型,double类型会使值变成64位失真。

在开发过程中,金额存储小数的方式很常见,我们可以采用String入参的形式定义BigDecimal(如果可以的话,将金额弄成整数在显示的时候除以位数,获取真正的金额)

使用compareTo方法比较两个金额的大小关系时:0表示相等,-1表示小于,1表示大于(上面那个例子就可以充分说明大小关系的比较)。在比较BigDecimal类型时,无法直接使用equals方法比较两个值是否相等,不过可以采用将金额转成字符串通过equals方法比较大小。