bigdecimal 减法结果为指数

bigdecimal subtraction results in exponential

我有以下代码。

BigDecimal b1 = new BigDecimal("1.12345678912345678");
    BigDecimal b2 = new BigDecimal("1.12345678912345678");
    System.out.println(b1.subtract(b2));

输出是: 0E-17

如何避免指数格式? bigdecimal 的 toPlainString 方法将 return String ,我不希望这样。我希望我的 bigdecimal 对象没有指数值。

您正在调用 println(Object) 方法,它在内部使用 Object.toString() 方法。

JavaDoc of BigDecimal.toString()

Returns the string representation of this BigDecimal, using scientific notation if an exponent is needed.

你关于 toPlainString() 方法和想要 bigdecimal 对象的陈述没有意义,因为区别仅在 toString() 方法和 toPlainString() 方法之间(两者都是return不同格式的字符串表示)。在这两种情况下,您都将拥有 相同的 BigDecimal 对象。区别仅在于打印时。