java中的BigDecimal.round()如何判断内部使用了哪种舍入方法

How to determine which rounding method is used internally by BigDecimal.round() in java

我正在使用 BigDecimal 根据所需的有效数字舍入输入,实际输入和所需的有效数字来自 JtextPane。这是示例代码;

String input = "1234.56";
String sf = "3";
String ans;
BigDecimal decRep = new BigDecimal(Double.parseDouble(input));
decRep = decRep.round(new MathContext(Integer.parseInt(sf)));
ans = String.valueOf(decRep.doubleValue());
System.out.println(ans);

这将导致 1230.0,这很好。但是如果向下舍入或者向上舍入也需要输出。

有办法确定吗?

如果我对你的问题理解正确,你想知道一个值相对于它的原始值是向上舍入还是向下舍入。这是最简单的方法:

public BigDecimal roundAndLog(String input, String sigFigs) {
  BigDecimal decimal = new BigDecimal(input);
  BigDecimal decimalRounded = decimal.round(new MathContext(Integer.parseInt(sigFigs)));

  int compared = decimalRounded.compareTo(decimal);
  if (compared == -1) {
    System.out.println("Rounded down!");
  } else if (compared == 0) {
    System.out.println("Value didn't change!");
  } else {
    System.out.println("Rounded up!");
  }
  return decimalRounded;
}