how do I use decimal numbers with bigintegers?
I would suspect the way I wrote, but obv it fails:
@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);
}
fails with:
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 [...]
BigInteger b = new BigInteger("20.20");
20.20 is not an integer.
What you want is:
BigDecimal b = new BigDecimal("20.20");
Int stays int no matter how hard you try ;-)
Try BigDecimal instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With