本文介紹了RoundingMode.UNNECESSARY引發異常的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我寫這段代碼是為了測試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));
}
}
推薦答案
這是精心設計的。請參閱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);
這篇關于RoundingMode.UNNECESSARY引發異常的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,