我正在尝试使用 Big decimal 将双精度数舍入,然后与另一个数字进行比较例如:
// Parse the string to extract the double and then put it into Big
// decimal
BigDecimal bdAns = BigDecimal.valueOf(Double.parseDouble("3.1419"));
System.out.println(bdAns);
BigDecimal bdCorr = BigDecimal.valueOf(Double.parseDouble("3.142"));
System.out.println(bdCorr);
System.out.println(bdCorr.precision() + " , " + bdAns.precision());
// Round down the value of the bdAns, so that the precision of bdAns and
// bdCorr matches. This code doesnt seem to work.
bdAns = BigDecimal.valueOf(bdAns).setScale(bdCorr.precision(),
BigDecimal.ROUND_UNNECESSARY);
System.out.println(bdAns);
System.out.println(bdAns.compareTo(bdCorr));
最后一个 println 正在打印 -1。但它们应该等于 3.1419 舍入到小数点后 3 位应该是 3.142。有人可以告诉我代码有什么问题吗?