Search code examples
javabigdecimal

How do I use "BigDecimal" in Java for my specific code?


I'm very new to programming in Java. I have been given an assignment in my school to solve the following exercise:

"Create two variables, each containing a number. Put out a message that shows how often the second number fits into the first one, and the rest (if there is one)" [I hope the wording is clear. I'm translating this from my native language german into english]

Now in general, I have solved the exercise like this (using Netbeans):

double numberOne = 10, numberTwo = 35.55;
double result, rest;
String conversion, numberOutput;

result = numberTwo / numberOne;
conversion = Double.toString(result);
int indexOfComma = conversion.indexOf(".");
numberOutput = conversion.substring(0, indexOfComma);
rest = numberTwo % numberOne;

System.out.println("The second number fits " + numberOutput + 
" times into the first one. The rest is: " + rest);

With the numbers provided, the system pops out this message:

"The second number fits 3 times into the first one. The rest is: 5.549999999999997"

I don't like the rounding error for the rest. I expected it to give out "5.55" like a human would type or write it. After a bit of googling around it seems that something called "BigDecimal" is the solution to my problem, but the explanations I found of how to implement this in Java go wayyy over my head.

Would you be so kind as to show me exactly where and how I need to use BigDecimal in the above code to get the desired output? I would also be happy to see any alternative solutions you can think of.


Solution

  • BigDecimal version of your code:

    BigDecimal numberOne = new BigDecimal("10");
    BigDecimal numberTwo = new BigDecimal("35.55");
    BigDecimal[] divRem = numberTwo.divideAndRemainder(numberOne);
    System.out.println("The second number fits " + divRem[0].stripTrailingZeros().toPlainString() + 
                       " times into the first one. The rest is: " + divRem[1].stripTrailingZeros().toPlainString());
    

    Output

    The second number fits 3 times into the first one. The rest is: 5.55