BigDecimal虽然相对double和float会降低性能,但是处理浮点数的时候不会丢失精度。故很多时候都会使用BigDecimal 做金钱运算.


数据库中decimal与Java中的BigDecimal相对应.


BigDecimal的stripTrailingZeros()是去掉多余的0。stripTrailingZeros()不光会去掉小数点后的没用的0,如果你的整数位的末尾数字也是0的话,它会将这个整数变成科学计数法。


故解决方法:

1. 将BigDecimal转为String,然后用正则替换.

2. 使用stripTrailingZeros().toPlainString()转为String,再用BigDecimal的String构造函数转


测试案例:


  public static void main(String[] args) {
        BigDecimal b1 = new BigDecimal(1231230.00);
        System.out.println(b1.stripTrailingZeros().toString());//result 1.23123E+6

        BigDecimal b2 = new BigDecimal(1231230.01000);
        System.out.println(b2.stripTrailingZeros().toString());//result 1231230.01000000000931322574615478515625
        System.out.println(b2.stripTrailingZeros().toPlainString());//result 1231230.01000000000931322574615478515625

        BigDecimal b3 = new BigDecimal("1231230.01000");
        System.out.println(b3.stripTrailingZeros().toString());//result 1231230.01
        System.out.println(b3.stripTrailingZeros().toPlainString());//result 1231230.01

        BigDecimal b4 = new BigDecimal("1231230");
        System.out.println(b4.stripTrailingZeros().toString());//result 1.23123E+6
        System.out.println(b4.stripTrailingZeros().toPlainString());//result 1231230

        System.out.println(new BigDecimal(b4.stripTrailingZeros().toPlainString()).toString());//result 1231230

    }