我正在使用 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;
}
关于java - 如何确定java中BigDecimal.round()内部使用哪种舍入方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62342916/