gpt4 book ai didi

java - RoundingMode.UNNECESSARY 抛出异常

转载 作者:搜寻专家 更新时间:2023-11-01 01:21:00 30 4
gpt4 key购买 nike

我编写此代码是为了测试 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:

Rounding mode to assert that the requested operation has an exact result, hence no rounding is necessary. If this rounding mode is specified on an operation that yields an inexact result, an {@code ArithmeticException} is thrown.

如果有需要舍入的内容,此模式专门用于抛出异常。

例子。下一个代码不会抛出异常。

    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);

关于java - RoundingMode.UNNECESSARY 抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30851417/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com