我写了这个来测试BigDecimal
的实际操作,但发现RoundingMode.UNNECESSARY
引发了异常。任何人都可以解释原因吗?
public class TestRounding2 {
public static void main(String args[]) {
Locale swedish = new Locale("sv", "SE");
BigDecimal pp; //declare variable pp=pounds pence
NumberFormat swedishFormat = NumberFormat.getCurrencyInstance(swedish);
Scanner scan = new Scanner(System.in);
System.out.println("ENTER POUNDS AND PENCE TO AT LEAST FIVE DECIMAL PLACES :");
pp = scan.nextBigDecimal();
BigDecimal pp1 = pp.setScale(2, RoundingMode.HALF_EVEN);
System.out.println("HALF_EVEN: £ " + pp1.toString());
System.out.println(swedishFormat.format(pp1));
BigDecimal pp2 = pp.setScale(2, RoundingMode.FLOOR);
System.out.println("FLOOR: £ " + pp2.toString());
System.out.println(swedishFormat.format(pp2));
BigDecimal pp3 = pp.setScale(2, RoundingMode.CEILING);
System.out.println("CEILING £: " + pp3.toString());
System.out.println(swedishFormat.format(pp3));
BigDecimal pp4 = pp.setScale(2, RoundingMode.HALF_DOWN);
System.out.println("HALF DOWN £: " + pp4.toString());
System.out.println(swedishFormat.format(pp4));
BigDecimal pp5 = pp.setScale(2, RoundingMode.HALF_UP);
System.out.println("HALF UP: £ " + pp5.toString());
System.out.println(swedishFormat.format(pp5));
BigDecimal pp6 = pp.setScale(2, RoundingMode.UP);
System.out.println("UP: £ " + pp6.toString());
System.out.println(swedishFormat.format(pp6));
BigDecimal pp7 = pp.setScale(2, RoundingMode.DOWN);
System.out.println("DOWN: £ " + pp7.toString());
System.out.println(swedishFormat.format(pp7));
BigDecimal pp8 = pp.setScale(2, RoundingMode.UP);
System.out.println("UP: " + pp8.toString());
System.out.println(swedishFormat.format(pp8));
}
}
答案 0 :(得分:11)
这是设计的。见javadoc:
舍入模式断言请求的操作具有精确性 结果,因此不需要舍入。如果这种舍入模式是 在产生不精确结果的操作上指定的, 抛出{@code ArithmeticException}。
如果有要回合的话,可以使用此模式专门抛出异常。
实施例。下一个代码不会抛出异常。
BigDecimal pp = new BigDecimal(7);
pp.setScale(2, RoundingMode.UNNECESSARY);
System.out.println(pp);
将7
更改为小数会导致异常,因为它现在必须绕过它:
BigDecimal pp = new BigDecimal(7.1);
pp.setScale(2, RoundingMode.UNNECESSARY);
// java.lang.ArithmeticException: Rounding necessary
System.out.println(pp);