java.lang.ArithmeticException: Rounding necessary

可能原因:对BigDecimal对象设置了精度,但是没有设置取舍方式,会报错java.lang.ArithmeticException: Rounding necessary。

@Test
public void testDecimal() {
	String str = "3.33333";
	BigDecimal decimal = new BigDecimal(str);
	try {
		System.out.println("setScale(2):" + decimal.setScale(2));
	} catch (Exception e) {
		e.printStackTrace();
	}
	try {
		System.out.println("setScale(2, RoundingMode.HALF_UP):" + decimal.setScale(2, RoundingMode.HALF_UP));
	} catch (Exception e) {
		e.printStackTrace();
	}
}
java.lang.ArithmeticException: Rounding necessary
	at java.math.BigDecimal.commonNeedIncrement(BigDecimal.java:4148)
	at java.math.BigDecimal.needIncrement(BigDecimal.java:4204)
	at java.math.BigDecimal.divideAndRound(BigDecimal.java:4112)
	at java.math.BigDecimal.setScale(BigDecimal.java:2452)
	at java.math.BigDecimal.setScale(BigDecimal.java:2512)
	at com.dz.MapTest.testDecimal(MapTest.java:63)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:483)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
	at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
	at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
setScale(2, , RoundingMode.HALF_UP):3.33

参考文章:http://www.xwood.net/_site_domain_/_root/5870/5874/t_c257486.html

你可能感兴趣的:(JavaSE)