如何将 "BigDecimal" in Java 用于我的特定代码?

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

我对 Java 中的编程还很陌生。我在学校布置了一项作业来解决以下练习:

"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)" [希望表述清楚。我正在将其从我的母语德语翻译成英语]

现在总的来说,我已经解决了这样的练习(使用 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);

根据提供的号码,系统弹出此消息:

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

我不喜欢其余部分的舍入误差。我希望它能像人类打字或写字一样给出“5.55”。经过一番谷歌搜索后,似乎名为 "BigDecimal" 的东西可以解决我的问题,但我在 Java 中找到的关于如何实现它的解释让我头疼。

您能告诉我在上面的代码中我需要在何处以及如何使用 BigDecimal 以获得所需的输出吗?我也很高兴看到您能想到的任何替代解决方案。

您的代码的 BigDecimal 版本:

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());

输出

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

你可以像这样使用 BigDecimal

BigDecimal a = BigDecimal.valueOf(10);
BigDecimal b = BigDecimal.valueOf(35.55);
BigDecimal c = b.divide(a, 3, BigDecimal.HALF_UP);
System.out.println(b + " / " + a + " = " + c);

或者你可以像这样使用舍入

System.out.printf("(int)(%.2f / %d) = %d%n", 35.55, 10, (int) (35.55 / 10));
System.out.printf("%.2f %% %d = %.2f%n", 35.55, 10, 35.55 % 10);

打印

floor(35.55 / 10) = 3
35.55 % 10 = 5.55