BigDecimal movePointRight和scaleByPowerOfTen有什么区别?

2022-09-02 13:40:57

使用以下代码:

BigDecimal x = new BigDecimal("34.5678");
BigDecimal a = x.movePointRight(3);
BigDecimal b = x.scaleByPowerOfTen(3);
BigDecimal c = x.movePointRight(-3);
BigDecimal d = x.scaleByPowerOfTen(-3);

a 和 b 都是 34567.8,c 和 d 都是 0.0345678。 并且都是 1 和 7。a.scale()b.scalec.scale()d.scale()

这两种方法在什么情况下会产生不同的结果?


答案 1
  • movePointRight如果负比例导致负比例,将防止出现负比例。
  • scaleByPowerOfTen不会阻止这种情况。

示例代码:

import java.math.BigDecimal;

public class BigDecimalScale {
  public static void main(String... args) {
    long base = 12345;
    int scale = 4;

    BigDecimal number = BigDecimal.valueOf(base, scale);
    System.out.println(number);
    BigDecimal pointRight = number.movePointRight(5);
    System.out.println(pointRight + "; my scale is " + pointRight.scale());
    BigDecimal scaleBy = number.scaleByPowerOfTen(5);
    System.out.println(scaleBy + "; my scale is " + scaleBy.scale());
  }
}

结果:

1.2345
123450; my scale is 0
1.2345E+5; my scale is -1

答案 2

我找到了答案。如果 x 声明为

BigDecimal x = new BigDecimal("34.5678", new MathContext(4));

则 a 的刻度为 0,但 b 的刻度为 -1。 给出 34570,得到 3.457E+4a.toString()b.toString()