BigDecimal 科学计数法 String 和普通 String

BigDecimal scientific notation String and normal String

我有这段代码

BigDecimal a = new BigDecimal("8000000");
BigDecimal b = new BigDecimal("80e5");
System.out.println("a equal b? " +a.compareTo(b));

BigDecimal resultA = a.divide(new BigDecimal("1000"), BigDecimal.ROUND_UP);
BigDecimal resultB = b.divide(new BigDecimal("1000"), BigDecimal.ROUND_UP);

System.out.println(resultA.compareTo(resultB));
System.out.println(resultA);
System.out.println(resultB);

结果

a equal b? 0
-1
8000
1E+5

我不明白?为什么 8000000/1000and round up 与 80e5/1000 and round up 不同?而java第一次说acompareb是0(等于?)

您正在使用的 divide 方法将结果的比例设置为原始对象的比例:

BigDecimal.divide(BigDecimal, int)

Returns a BigDecimal whose value is (this / divisor), and whose scale is this.scale(). If rounding must be performed to generate a result with the given scale, the specified rounding mode is applied.

由于您从“80e5”创建了 b,它的小数位数是 -5,并且 divide 必须将其结果四舍五入到 1e+5:

jshell> var b = new BigDecimal("80e5");
b ==> 8.0E+6

jshell> b.scale()
 ==> -5

jshell> var c = b.divide(new BigDecimal("1000"), BigDecimal.ROUND_UP);
c ==> 1E+5

jshell> c.scale()
 ==> -5

为了解决这个问题,您可以在除法时为结果设置您想要的比例:

jshell> b.divide(new BigDecimal("1000"), 0, BigDecimal.ROUND_UP);
 ==> 8000