Java代码:
public class BigDecimalDemo {
public static void main(String[] args) {
BigDecimal bd2=BigDecimal.valueOf(11);
BigDecimal bd3=new BigDecimal("2.3");
BigDecimal bdDiv = bd2.divide(bd3,38,RoundingMode.HALF_UP);
System.out.println(bdDiv);
BigDecimal bdDivDOWN = bd2.divide(bd3,10, RoundingMode.HALF_DOWN);
System.out.println(bdDivDOWN);
BigDecimal bdDivUP = bd2.divide(bd3,10, RoundingMode.HALF_UP);
System.out.println(bdDivUP);
}
}
输出:
4.78260869565217391304347826086956521739
4.7826086957
4.7826086957
题:
RoundingMode.HALF_DOWN和RoundingMode.HALF_UP的输出为何相同?
最佳答案
好吧,RoundingMode.HALF_DOWN
的javadoc说:
如果舍弃的分数> 0.5,则表现为RoundingMode.UP;否则,其行为与RoundingMode.DOWN相同。
而RoundingMode.HALF_UP
的Javadoc说:
如果舍弃分数≥0.5,则表现为RoundingMode.UP;否则,表现为RoundingMode.DOWN
在您的示例中,第二级和第三级中的废弃分数是0.5217391304347826086956521739,该分数> 0.5,因此两者的行为均RoundingMode.UP
。
仅当丢弃分数精确为0.5时,您才会看到不同的结果。
例如,以下内容:
BigDecimal bd2=BigDecimal.valueOf(11.12345678955);
BigDecimal bd3=new BigDecimal("1");
BigDecimal bdDiv = bd2.divide(bd3,38,RoundingMode.HALF_UP);
System.out.println(bdDiv);
BigDecimal bdDivDOWN = bd2.divide(bd3,10, RoundingMode.HALF_DOWN);
System.out.println(bdDivDOWN);
BigDecimal bdDivUP = bd2.divide(bd3,10, RoundingMode.HALF_UP);
System.out.println(bdDivUP);
将输出
11.12345678955000000000000000000000000000
11.1234567895
11.1234567896