Java 如何使用大整数和小数?
如何使用带大整数的十进制数 我会怀疑我的写作方式,但显然它失败了:Java 如何使用大整数和小数?,java,junit,biginteger,Java,Junit,Biginteger,如何使用带大整数的十进制数 我会怀疑我的写作方式,但显然它失败了: @Test public void bigIntegerTestCalcs() { BigInteger a = new BigInteger("20"); BigInteger b = new BigInteger("20.20"); BigInteger result = a.add(b); assertEquals(new BigInteger("40.20"), result); }
@Test
public void bigIntegerTestCalcs() {
BigInteger a = new BigInteger("20");
BigInteger b = new BigInteger("20.20");
BigInteger result = a.add(b);
assertEquals(new BigInteger("40.20"), result);
}
在以下情况下失败:
java.lang.NumberFormatException: For input string: "20.20"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:492)
at java.math.BigInteger.<init>(BigInteger.java:338)
at java.math.BigInteger.<init>(BigInteger.java:476)
at src.test.unit.CalculatorTest.bigIntegerTestCalcs(CalculatorTest.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
at org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:105)
at org.unitils.UnitilsJUnit4TestClassRunner$TestListenerInvokingMethodRoadie.runTestMethod(UnitilsJUnit4TestClassRunner.java:174)
at org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
at [...]
java.lang.NumberFormatException:对于输入字符串:“20.20”
位于java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
位于java.lang.Integer.parseInt(Integer.java:492)
在java.math.biginger.(biginger.java:338)
在java.math.biginger.(biginger.java:476)
位于src.test.unit.CalculatorTest.bigIntegerTestCalcs(CalculatorTest.java:40)
在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)处
在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)中
在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)中
位于java.lang.reflect.Method.invoke(Method.java:601)
位于org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66)
位于org.junit.internal.runners.MethodRoadie.runTestMethod(MethodRoadie.java:105)
位于org.unitils.UnitilsJUnit4TestClassRunner$TestListenerInvokingMethodRoadie.runTestMethod(UnitilsJUnit4TestClassRunner.java:174)
位于org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
在[…]
biginger
用于整数(即不带小数点的数字),您尝试使用它处理浮点数。对于这种用法,BigDecimal
无论您如何努力,Int都保持Int;-)
试试BigDecimal
BigInteger b = new BigInteger("20.20");
20.20不是整数
你想要的是:
BigDecimal b = new BigDecimal("20.20");
为什么你认为小数可以和整数连用?