Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use BigInteger and decimal numbers?

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 [...]
like image 764
membersound Avatar asked Feb 22 '12 14:02

membersound


2 Answers

BigInteger b = new BigInteger("20.20");

20.20 is not an integer.

What you want is:

BigDecimal b = new BigDecimal("20.20");
like image 79
TacticalCoder Avatar answered Oct 04 '22 03:10

TacticalCoder


Int stays int no matter how hard you try ;-)

Try BigDecimal instead.

like image 43
Matthias Avatar answered Oct 04 '22 03:10

Matthias